2

I need an regular expression to match, in a sentence, words within brackets. For example:

"this is [stack]overflow. I [[love]this[website]]."

what i want to match from the sentence above are the words stack, love and website.

I've tried the folowing regexp \[(.*[^\]\[])\] but it doesn't work.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
Jdoe
  • 69
  • 1
  • Welcome to [SO]; please review the [faq]. – zzzzBov Dec 07 '12 at 18:40
  • 2
    Please specify the regex flavor (as required in the tag description). – Denys Séguret Dec 07 '12 at 18:41
  • 4
    I find the votes a little harsh on this question. The question could have been better asked but that's neither so easy nor so localized. – Denys Séguret Dec 07 '12 at 18:43
  • 2
    Was this downvoted so much just because it didn't include a question mark? The OP clearly described the problem and showed what he tried... Too localized? You could say that about almost all regex questions. – Andrew Clark Dec 07 '12 at 18:45

2 Answers2

4

The following should work:

\[([^\[\]]*)\]

Example: http://www.rubular.com/r/uJ0sOtdcgF

Explanation:

\[           # match a literal '['
(            # start a capturing group
  [^\[\]]*     # match any number of characters that are not '[' or ']'
)            # end of capturing group
\]           # match a literal ']'
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • thank you for the answer F.J. It works. I'm sorry for not following posting policy on this website but i'm a newbie with a need of urgent helping. – Jdoe Dec 07 '12 at 18:50
  • @Jdoe - Your question was very close to good. Next time make sure your title attempts to describe your problem, "I need a regular expression" is too vague (I edited your question to fix this). Also, even though it was clear what you wanted, include a question. Something like "How can I fix this?" to the end would be sufficient. – Andrew Clark Dec 07 '12 at 18:52
  • 1
    @Jdoe - And with regex questions, include the language or tool you are using. – Andrew Clark Dec 07 '12 at 18:54
1

Try doing this in a :

$ echo 'this is [stack]overflow. I [[love]this[website]]' |
    grep -oP '\[+\K[^\]]+'
stack
love
website

This works with PCRE & perl engines.

EXPLANATIONS

\[           # match a literal '['
+            # one (preceding character) or more
\K           # "reset" the regex to null
[^]          # excluding class, here a literal \]
\]           # match a literal ']'

explanations about \K trick

Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • This will match `this[website` in `[this[website]]`. Also, as your link says, it will not work in most flavors, which is a shame for such a simple requirement. – Kobi Dec 07 '12 at 18:59