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:
"[one]"
or "[one] [two][three].[four]"
)."[one]"
or "[two ]"
or "[ three ]"
."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
\[\s*(\S+?)\s*\]
Explanation
\[ # a literal "[" \s* # any number of white space (\S+?) # at least one non white-space character, non-greedily (group 1) \s* # any number of white space \] # a literal "]"
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 \S
is very unspecific. If you have anything more specific in terms of what "a word" is for you - by all means, use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With