I'm trying to write a RegEx that would match the following patterns using String.match
:
"rgb(252, 246, 253)" // ["252", "246", "253"]
"hsl(12, 23%, 43%)" // ["12", "23%", "43%"]
"myfunc(342, 2341%, 0.5%)" // ["342", "2341%", "0.5%"]
"(723, 456a, 123)" // ["723", "456a", "123"]
"12 4324 0.6%" // ["12", "4324", "0.6%"]
"hello world word3" // ["hello", "world", "word3"]
"keep, writing, more, words, asmuch" // ["keep", "writing", "more", "words", "asmuch"]
"fn(hello world word3)" // ["hello", "world", "word3"]
The scope must be within the optional (first) brackets - if they don't exist, the whole string can be considered. Within that scope, just the comma/space separated tokens need to be matched.
I've tried different approaches, notably /\(([^()]*)\)/g
and /[^\s(),] /g
, but it still did not quite get there.
CodePudding user response:
You can use a lookahead to check if there is not an opening (
ahead.
[^,)(\s] (?![^(]*\()
See this demo at regex101 (the \n
in multiline demo is to stay in line)
[^,)(\s]
negated class to match one or more characters not in the list(?![^(]*\()
looks ahead if no opening parentheses is ahead