tags:

views:

192

answers:

3

Simple regex question. I have a string on the following format:

this is a [sample] string with [some] special words. [another one]

What is the regular expression to extract the words within the square brackets, ie.

sample
some
another one

Note: In my use case, brackets cannot be nested.

+2  A: 

This should work out ok:

\[([^]]+)\]
jasonbar
Eugh, this question makes for one simple-but-ugly regex. :)
Ipsquiggle
Also, the escape inside the character class should be unnecessary: a `]` immediately following the `^` in a character class doesn't need to be escaped.
Ipsquiggle
@Ipsquiggle: oops, you're right. Thanks!
jasonbar
+2  A: 

Can brackets be nested?

If not: \[([^]]+)\] matches one item, including square brackets. Backreference \1 will contain the item to be match. If your regex flavor supports lookaround, use

(?<=\[)[^]]+(?=\])

This will only match the item inside brackets.

Tim Pietzcker
+3  A: 

You can use the following regex globally:

\[(.*?)\]

Explanation:

  • \[ : [ is a meta char and needs to be escaped if you want to match it literally.
  • (.*?) : match everything in a non-greedy way and capture it.
  • \] : ] is a meta char and needs to be escaped if you want to match it literally.
codaddict
The other answer's method, using `[^]]` is faster than non-greedy (`?`), and also works with regex flavours that don't support non-greedy. However, non-greedy looks nicer.
Ipsquiggle