Given the following example string: "[ One].[Two ].[ Three ].[Four]"
I want to match “One”; “Two”, “Three” and “Four”.
In other words: I need to get the word between the brackets, regardless how many white spaces are surround this word.
I’ve tried it with the following expression:
(?<=\[)(?s)(.*?)(?=\s*\])
That results in " One", "Two", " Three" and "Four".
EDIT:
It’s a little bit more complicated than I first tought it would be:
- There are many (at least one) word(s) encapsulated by brackets which might seperated by an arbitrary char (e.g.
"[one]"or"[one] [two][three].[four]"). - The brackets contain one single word and many, or even no whitespaces (e.g.
"[one]"or"[two ]"or"[ three ]". - These blocks of words and there enclosing brackets are surrounded by a known sequence of chars:
"These words [word-1] .. [word-n] are well known"or
"These words [word-1] .. [word-n] are well known".
Please note that "[word-1] .. [word-n]" just stands for an arbitrary count of the blocks described above.
I want to match just the single word(s) between the brackets and eliminate the surround sequence ("These words" and "are well known") as well as possibly existing whitespaces within the brackets and between the blocks. In addition, the possibly existing char (it couldn’t be more than only one) between the blocks should be eliminiated, too.
Hope that wasn’t too weird 😉
You can use this, with the “global” flag enabled
Explanation
EDIT:
@Kobi noted that
\S+?can actually match the]in targets like"[ One]". So for a moment, group 1 would contain"One]".But then there still is the
\]at the end of the regex, at which point the regex engine would backtrack and give the"]"to\], so the expression can succeed.It is vitally important to use on-greedy matching here (
\S+?, as opposed to\S+). I got that wrong in the first version of my answer as well.Further, the
\Sis very unspecific. If you have anything more specific in terms of what “a word” is for you – by all means, use it.