Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get array of tokens in an optional capture group

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 after each match if no opening parentheses is ahead
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading