Search code examples
regexstringsubstringdelimiterpcre

Second-to-last occurrence of delimiter-split string


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,

Solution

  • 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