0

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

1
  • it helps if you tag your question with the appropriate programming language Commented Dec 11, 2009 at 11:48

2 Answers 2

1
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].

Sign up to request clarification or add additional context in comments.

Comments

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

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.