1

Given the following strin:

var s = "my [first] ga[m]e and [abc]de]\nThe [Game]"

Which regex do I use to match:

0 - [first]
1 - [abc]de]
2 - [Game]

I have tried var pattern2 = new Regex(@"\W\[.*?\]\W"); but it doesn't find [Game]

I also want to be able to match "[my] gamers\t[pro]"

0 - [my]
1 - [pro]
Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522
Soni Ali
  • 17,252
  • 15
  • 42
  • 49
  • possible duplicate of: http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets with further reading at: http://stackoverflow.com/questions/524548/regular-expression-to-detect-semi-colon-terminated-c-for-while-loops/524624#524624 – hometoast Oct 12 '12 at 14:20
  • I don't think it's a duplicate of that. He's not looking for balanced brackets (`[abc]de]` is not balanced), he's looking for brackets that are at word boundaries. – Barmar Oct 12 '12 at 15:05

2 Answers2

4
\[[^\[]{2,}\]

Explanation:

\[         # Match a [
[^\[]{2,}  # Match two or more non-[ characters
\]         # Match ]

See it on RegExr.

Tim Pietzcker
  • 297,146
  • 54
  • 452
  • 522
  • Good but I still had to think about it despite the explanation. :) – Chris Oct 12 '12 at 14:28
  • I don't think this is working. I changed the input to `my [first] ga[m]e and ]de]\nThe [Game]` and it matched `[m]e and ]de]`. – Barmar Oct 12 '12 at 15:09
  • @Barmar: Yes, the regex allows any characters except `[` between the two delimiting brackets. The specs aren't very clear on what is and what isn't allowed in a "word". Perhaps `\[\S{2,}\]` would be a better fit (allowing only non-space characters between the brackets) - but that remains for the OP to specify. – Tim Pietzcker Oct 12 '12 at 15:33
  • I'd just put both left and right brackets in the negative class like so: `\[[^[\]]{2,}\]`. +1. – ridgerunner Oct 12 '12 at 15:44
  • @ridgerunner: That won't work because some of the examples contain a closing bracket as part of the word to be matched... – Tim Pietzcker Oct 12 '12 at 16:01
0

You need to match beginning and end of the string explicitly, in addition to non-word characters:

(?:^|\W)\[(.*?)\](?:$|\W)

The capture group will get the words inside the brackets.

Barmar
  • 596,455
  • 48
  • 393
  • 495