21

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

KBBWrite
  • 4,373
  • 2
  • 20
  • 22

4 Answers4

42

[ 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.

moinudin
  • 134,091
  • 45
  • 190
  • 216
13
^\[.*\]$

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 ]
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • I'm not sure whether yours or thecoop's answer is the best, but I assume yours because the OP never mentioned that there should be ANY characters between the [ and ], and therefore your `*` is a better match than thecoop's `+`. – Bazzz Feb 21 '11 at 13:33
7

This should work:

^\[.+\]$

^ is 'start of string'
\[ is an escaped [, because [ is a control character
.+ matches all strings of length >= 1 (. is 'any character', + means 'match previous pattern one or more times')
\] is an escaped ]
$ is 'end of string'

If you want to match [] as well, change the + to a * ('match zero or more times')

Then use the Regex class to match:

bool match = Regex.IsMatch(input, "^\[.+\]$");

or, if you're using this several times or in a loop, create a Regex instance for better performance:

private static readonly Regex s_MyRegexPatternThingy = new Regex("^\[.+\]$");

bool match = s_MyRegexPatternThingy.IsMatch(input);
thecoop
  • 45,220
  • 19
  • 132
  • 189
2

You need to use escape character \ for brackets.
Use .+ if you like to have at least 1 character between the brackets or .* if you accept this string: [].

^\[.*\]$
HuBeZa
  • 4,715
  • 3
  • 36
  • 58