Regex to extract (full match) word from last but one, between comma?

Viewed 132

How to return the word example in the result column? the closest I got was [\W]{2,}[^,\W].+[?=,]

id text my result (Full match) expected (Full match)
1 wordA, worldB, wordC , worldB, wordB
2 wordF wordY, worldZ, wordn, wordM , worldZ, wordn, wordn
3 wordg wordt, worldl, wordq, wordk, wordr , worldl, wordq, wordk, wordk
4 this is a test, capturing, a word , capturing, capturing
2 Answers

You may try this one:

(?!\s)[^,]+?(?=\s*,[^,]*$)
  • (?!\s) make sure is not capturing the first white space
  • [^,]+? anything that not a comma, non-greedy
  • (?=\s*,[^,]*$) possitive look ahead, there is a comma seperated word in front of it before the end of the string

It also trims the white spaces at both ends.

See the proof

This regex looks at the end of the string $, capturing the word (\w+) before the last comma \, and last word [\w\s]+

https://regex101.com/r/42NELQ/1

(\w+)\,[\w\s]+$
Related