tags:

views:

72

answers:

2

Hello there,

I have been using Regex to match strings embedded in square brackets [*] as:

new Regex(@"\[(?<name>\S+)\]", RegexOptions.IgnoreCase);

I also need to match some codes that look like: [TESTTABLE: A, B, C, D]

it has got spaces, comma, colon

Can you please guide me how can I modify my above Regex to include such codes.
P.S. other codes have no spaces/special charaters but are always enclosed in [...].

A: 
/\[([^\]:])*(?::([^\]]*))?\]/

Capture group 1 will contain the entire tag if it doesn't have a colon, or the part before the colon if it does.

Capture group 2 will contain the part after the colon. You can then split on ',' and trim each entry to get the individual parts.

Anon.
+1  A: 
Regex myregex = new Regex(@"\[([^\]]*)]")

will match all characters that are not closing brackets and that are enclosed between brackets. Capture group \1 will match the content between brackets.

Explanation (courtesy of RegexBuddy):

Match the character “[” literally «\[»
Match the regular expression below and capture its match into backreference number 1 «([^\]]*)»
   Match any character that is NOT a ] character «[^\]]*»
      Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
Match the character “]” literally «]»

This will also work if you have more than one pair of matching brackets in the string you're looking at. It will not work if brackets can be nested, e. g. [Blah [Blah] Blah].

Tim Pietzcker