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

regex works but not any more when adding \s

My regex works (extracting abc, bed, ced), I just wanted to refine by excluding space but surprisingly adding \s wrecked everything :

https://regex101.com/r/IJavxn/2

  let test = `test(abc, bed, ced)`;

  let regex = /(?<=[\(,])[^,\)]+/g
  alert(test.match(regex)); 

  let regex2 = /(?<=[\(,])[^,\)\s]+/g
  alert(test.match(regex2)); 

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 :

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 )

Regex demo

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