tags:

views:

194

answers:

2

Related to my previous 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 either square or curly brackets, ie.

{is}
[sample]
[some]
{special}
[another one]

Note: In my use case, brackets cannot be nested. I would also like to keep the enclosing characters, so that I can tell the difference between them when processing the results.

+2  A: 

This one seems to work:

[[{].*?[}\]]

Or this one:

\[.*?\]|{.*?}

If you want to catch the cases mentioned in the comments below.

You can use an online regex tester to try these things out. I think http://gskinner.com/RegExr/ is one of the more user-friendly options.

Carl Norum
This will fail in the case of [ ... }.
Robert P
Edited to remove an extraneous `\`.
Carl Norum
@Robert, he said that doesn't happen in his text, right?
Carl Norum
@Carl, no he said [{foo} [bar]] (example of nesting) didn't happen.
Matthew Flaschen
Brackets can't be nested means to me [ [ ] ], which is a classic case that regular expressions fail on.
Robert P
His example string doesn't contain such a thing. I will edit to change that.
Carl Norum
@Carl: You can match a [ with `\[`. Why use `[[]`?
KennyTM
@Kenny, changed - I was just editing my previous entry, should be fixed already.
Carl Norum
+5  A: 

Simply or (|) the different things you wish to match together:

\[.*?\]|\{.*?\}

Robert P