1

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?

2
  • I've found the free Rad Software Regular Expression Designer immensely useful when writing regular expressions. It includes a built-in reference and the ability to check your regex: radsoftware.com.au/regexdesigner Commented Jul 22, 2010 at 5:29
  • btw, it would be helpful if you'd clarify whether you want a regex to validate/match the string or to extract/capture the two elements in the string. Commented Jul 22, 2010 at 5:38

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

How do i extract the strings within the "[]"? so it will pull out somestring and anotherstring.
@ronald-yoh: Use the grouping operators.
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.
2
@"(\[[^\]]+\]){2}"

I think (my head hurts a little now).

Note, this will match anything between [ and ].

1 Comment

Note: if the string is [s[omest[ring][anotherstring], it will also match successfully, which you may not want.
0

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!

1 Comment

Note that you need to escape the backslash in the string (before the regex "sees" it) by using "\\" or @"\".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.