My first regex works (extracting "abc"
, " bed"
and " ced"
). I wanted to refine by excluding spaces, but adding \s
meant only "abc"
matched:
const test = "test(abc, bed, ced)";
const regex = /(?<=[\(,])[^,\)] /g
console.log(test.match(regex)); // ["abc", " bed", " ced"]
const regex2 = /(?<=[\(,])[^,\)\s] /g
console.log(test.match(regex2)); // ["abc"]
https://regex101.com/r/IJavxn/2
CodePudding user response:
In the pattern (?<=[(,])[^,\)\s]
the lookbehind assertion (?<=[(,])
checks that from the current position there is no (
or ,
directly to the left.
If the following character class [^,\)\s]
also does not allow to match a space, then there will only be a match for the first occurrence as there is no space between the parenthesis and abc in (abc
As you are already using a lookbehind, you can exclude the whitespaces as well and use a quantifier. Then start the match also excluding a whitespace char.
The \s*
in the lookbehind here (?<=[(,]\s*)
allows zero of more spaces to be present.
(?<=[(,]\s*)[^\s,)]
(?<=
Positive lookbehind, assert that from the current position what is to the left is[(,]\s*
Match a single char other than(
or,
followed by optional whitespace chars
)
Close the lookbehind[^\s,)]
Match 1 characters other than a whitespace char or , or)