van
van

Reputation: 9449

regex to find 4th comma from the end of line

I need a regular expression to match the forth comma from the end of the line, my line end in a comma.

For example, I'd like to select the comma after the G in the line below:

A,B,C,D,E,F,G,H,I,J,

Upvotes: 6

Views: 1847

Answers (2)

Unihedron
Unihedron

Reputation: 11051

You can use a quantifier and then backtrack:

Single-line input version (No newlines)

/.*\K,(?=(?:[^,]+,){3})/

Single-line matching version: (Newlines present)

/.*\K,(?=(?:[^,\n]+,){3})/

Multi-line matching version:

/.*\K,(?=(?:[^,]+,){3})/s

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838736

You can do this using a lookahead:

,(?=(?:[^,]*,){3}[^,]*$)

See it working online: Rubular

Upvotes: 6

Related Questions