cnauber
cnauber

Reputation: 443

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

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

Upvotes: 2

Views: 623

Answers (2)

symlink
symlink

Reputation: 12208

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]+$

Upvotes: 1

Hao Wu
Hao Wu

Reputation: 20867

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

Upvotes: 1

Related Questions