Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx Starts with [ and ending with ]

Tags:

c#

regex

What is the Regular Expression to find the strings starting with [ and ending with ]. Between [ and] all kind of character are fine.

like image 385
KBBWrite Avatar asked Feb 21 '11 13:02

KBBWrite


People also ask

How do I specify start and end in regex?

To match the start or the end of a line, we use the following anchors: Caret (^) matches the position before the first character in the string. Dollar ($) matches the position right after the last character in the string.

Which matches the start and end of the string?

Explanation: '^' (carat) matches the start of the string. '$' (dollar sign) matches the end of the string. Sanfoundry Certification Contest of the Month is Live. 100+ Subjects.

How do you specify an end in regex?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.

Does regex have to start with?

As usual, the regex engine starts at the first character: 7. The first token in the regular expression is ^. Since this token is a zero-length token, the engine does not try to match it with the character, but rather with the position before the character that the regex engine has reached so far.


2 Answers

[ and ] are special characters in regular expressions, so you need to escape them. This should work for you:

\[.*?\]

.*? does non-greedy matching of any character. The non-greedy aspect assures that you will match [abc] instead of [abc]def]. Add a leading ^ and trailing $ if you want to match the entire string, e.g. no match at all in abc[def]ghi.

like image 65
moinudin Avatar answered Oct 04 '22 19:10

moinudin


^\[.*\]$

will match a string that starts with [ and ends with ]. In C#:

foundMatch = Regex.IsMatch(subjectString, @"^\[.*\]$");

If you're looking for bracket-delimited strings inside longer strings (e. g. find [bar] within foo [bar] baz), then use

\[[^[\]]*\]

In C#:

MatchCollection allMatchResults = null;
Regex regexObj = new Regex(@"\[[^[\]]*\]");
allMatchResults = regexObj.Matches(subjectString);

Explanation:

\[        # match a literal [
 [^[\]]*  # match zero or more characters except [ or ]
\]        # match a literal ]
like image 40
Tim Pietzcker Avatar answered Oct 04 '22 19:10

Tim Pietzcker