Colin
Colin

Reputation: 23

Regex: How to parse nth match

I can't get this regex to parse the nth token/match. Matching tokens is easy, but I can't extract the exact match I need.

Regex: (?:\w+){2}(\w+)

Input:

001.002.003.004
450000.459999.1.0.1.0

Using (\w+) matches all the tokens. works perfectly. But I can't extract the nth (e.g. 3rd or 4th).

Your help is appreciated.

Upvotes: 0

Views: 149

Answers (2)

Mecki
Mecki

Reputation: 133199

(?:\w+){2} won't work as it doesn't match the period. \w+ matches up to the period and that's where the matching ends as nothing in your regex matches period.

Try (?:\w+\.){N}(\w+) where N is the number of groups you want to skip. So to capture the 3rd value, N would be 2, to capture the 4th it would be 3 and so on.

Upvotes: 1

Paker
Paker

Reputation: 2552

I think this regexp should solve your problem: /(\w+)/g

See https://regex101.com/r/vSqV7m/1/

If your tokens are digits only using \d will be even better: /(\d+)/g

Upvotes: 0

Related Questions