Home > OS >  Regex match left side of comma-separated expression
Regex match left side of comma-separated expression

Time:04-27

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

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

CodePudding user response:

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

CodePudding user response:

This seems to work:

\w (?= =)

See live demo.

In English, words characters the are followed by " =".

  • Related