0

What is the regex to extract second-to-last substring when the string is to be split by specified delimiter?

E.g., the delimiter is comma , - I would only like to match words "matchX".

a,b,match1,c
a,match2,b
match3,a
match4,
,,match5,a
,,match6,
ZygD
  • 22,092
  • 39
  • 79
  • 102

2 Answers2

1

Depending on the use case, one of the below can do it.

When the substring contains any symbol including spaces:

([^,\n]+),[^,]*$

When the substring contains only alphanumeric characters and underscore _:

(\w+),[^,]*$

When the substring contains only alphanumeric characters:

([[:alnum:]]+),[^,]*$

https://regex101.com/r/e987Xr/1

ZygD
  • 22,092
  • 39
  • 79
  • 102
1

Another option could be just a match with a negative lookahead assertion, and exclude matching newlines before asserting the end of the string.

\w+(?=,[^,\n]*$)

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70