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 match left side of comma-separated expression

Desire to create a regex to match the left side of an expression that is comma-separated as follows, preferably ignoring any whitespace:

abc = a1, def = b2, ghi = c3

Expression would match abc def and ghi

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

Have used this regex so far (?<=,).*?(?=\=), however it doesn’t match the first value and does not ignore whitespace.

>Solution :

Your pattern does not match the first value because the positive lookbehind (?<=,) asserts a comma to the left which is not there for the first value in the example string.

The pattern does not ignore whitespace because in this part .*?(?=\=) the "dot star" can match (including spaces) to the point that the assertion (?=\=) is true.

One option to get the first value is to use a capture group and match the pattern that follows ending either on a comma or assert the end of the string.

(\w+)\s+=\s+\w+(?:,|$)

Explanation

  • (\w+) Capture 1+ word characters in group 1
  • \s+=\s+ Match = between whitespace chars
  • \w+ Match 1+ word characters
  • (?:,|$) Match either a comma or assert the end of the string

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