Magicskid
Magicskid

Reputation: 33

How Do You Match the Last Comma and Space In a List With Regex?

For example, say the list is...

Hello, World, Test, One, Ten

How would I match the last comma and space (after 1), but also not match "Ten" with it?

I've tried (,\s)$ and (,\s)[^,]*$ but that doesn't do exactly what I'm looking for...

Upvotes: 1

Views: 244

Answers (2)

The fourth bird
The fourth bird

Reputation: 163577

If you don't want to match Ten you can change the match into a lookahead.

,\s(?=[^,]*$)

The pattern matches

  • ,\s Match a comma and a whitespace char
  • (?= Positive lookahead, assert to the right
    • [^,]*$ match 0+ occurrences other than , till the end of the string
  • ) Close lookahead

Note that \s and [^,]* can also match a newline.

Regex demo

Upvotes: 1

Mohammad Ali Amini
Mohammad Ali Amini

Reputation: 303

try this:

(,\s)(?:\w+)$

RegEx Demo

Upvotes: 0

Related Questions