tags:

views:

59

answers:

4

Hi there,

been trying the to figure out the escape char for "["and "]" in regex. I have the following pattern of string and this string is the actual string:

[somestring][anotherstring]

So the string will start with "[" followed by somestring and followed by with "]" and followed by "[" and followed by anotherstring and followed by "]".

can anyone please suggest?

A: 

Escape the [ and ] with a '\'.

ie "\[[A-Za-z]*\]\[[A-Za-z]*\]"

http://gskinner.com/RegExr/ This site is awesome for playing around with regexes.

Have Fun!

Iain
Note that you need to escape the backslash in the string (before the regex "sees" it) by using `"\\"` or `@"\"`.
Kobi
+2  A: 
@"(\[[^\]]+\]){2}"

I think (my head hurts a little now).

Note, this will match anything between [ and ].

leppie
Note: if the string is `[s[omest[ring][anotherstring]`, it will also match successfully, which you may not want.
Jaroslav Jandek
@Jaroslav Jandek: Very good point :)
leppie
A: 

Escape the [ and ] characters using a backslash \:

\[\w+\]\[\w+\]

Note that \w is a special character class that translates to [A-Za-z0-9]. The backslash has significance and is not used in escaping the w.

BoltClock
+2  A: 

If it is only 1 level and you want to parse out the strings, then you do not need RegEx:

string composition = "[somestring][anotherstring]";
string[] stringSeparators = new string[] {"][", "[", "]"};
string[] s = composition.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

If you want to match for the exact pattern:

Regex r = new Regex(@"^(\[[^\[\]]+\]){2}$");

Edit - to answer with syntax-highlighted code to the commenter: For parsing out the string Regex way using groups, you can use:

foreach (Match match in Regex.Matches(composition, @"\[([^\[\]]+)\]"))
  Console.WriteLine(match.Groups[1].Value);
Jaroslav Jandek
How do i extract the strings within the "[]"? so it will pull out somestring and anotherstring.
@ronald-yoh: Use the grouping operators.
leppie
I'm fairly new with regex.. can u please give me an example?
@leppie: +1.@ronald-yoh: Added a Regex-way parsing to the answer.
Jaroslav Jandek