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.
This should work out ok:
Will capture content without brackets
(?<=\[)
- positive lookbehind for[
.*?
- non greedy match for the content(?=\])
- positive lookahead for]
EDIT: for nested brackets the below regex should work:
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, useThis will only match the item inside brackets.
(?<=\().*?(?=\))
works good as per explanation given above. Here's a Python example:This code will extract the content between square brackets and parentheses
Above should work given the following explaination
characters within square brackets[] defines characte class which means pattern should match atleast one charcater mentioned within square brackets
\s specifies a space
+ means atleast one of the character mentioned previously to +.