I have the following string:
[I need some fresh air H2O]
.
What’s the RegEx that matches the following words?
I
,need
,some
,fresh
,air
,H2O
.
Basically, each word inside the square brackets. I searched everywhere, couldn’t find it. Every result points to a whole match, such as I need some fresh air H2O
(check links below).
Can anyone help?
I’m currently at this RegEx:
(?<=[).+?(?=])
But it captures the whole sentence:
I need some fresh air H2O
I’m using the https://regexr.com/ engine (I assume it’s javascript), but any engine pattern would suffice.
2
Answers
You can use
str.slice(1, -1).split(/s+/)
ormatch()
method using:/bw+b/g
:b
is a word boundary./[^[]rns]+/g
: means all chars except those included in the[]
.Prints
It’s rather simple to match all words in a string:
w+
w
matches alphanumeric characters and underscores. This assumes that you use a "global search" which repeatedly applies the pattern on the remaining string after each match. In javascript this would be/w+/g
.