Regular expression: extract everything before comma or all text if no comma, except a specific digit comma digit combination

Viewed 329

I have a series of strings from whom I want to extract a part:

string match
difluoroethane, HFC-152a difluoroethane
difluoroethane HFC-152a difluoroethane HFC-152a
1,1-difluoroethane, HFC-152a 1,1-difluoroethane
1,1-difluoroethane HFC-152a 1,1-difluoroethane HFC-152a

basically everything before the first comma OR the entire string if there's no comma, but include in the match those cases of digit comma digit which are part of the compound name.

so far that's what I tried

^(.{2,}?),

but it only works for line 3 in the table

1 Answers

You may use this regex:

^(?:\d+,\d+)?[^,]+

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:\d+,\d+)?: Match an optional digits,digits at the start
  • [^,]+: Match 1+ non-comma characters
Related