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,
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,
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:]]+),[^,]*$
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]*$)