Regex capture n-th match

Is there a way using regex to return the nth occurrence? I searched the forums and found a solution that goes beyond the scope of the regular expression itself (i.e. needs support from a programming language).

Example: Regex:

(?:\$(\d+(?:,\d{3})*\.\d{2})) 

Input:

  thiscanbeanything$25.74thiscanbesomethingelse alsowithnewlines$533.63thisonetoo$54.32plusthis$62.42thisneverends 

I will need to extract the first (this is 25.74). Later I may need to extract the third one (this is 54.32).

Currently my regular expression matches all occurrences. I could get the nth element after matches, but my question is: is it possible to do this only with a regular expression (i.e. a regular expression will return only the element I need)?

Thanks!

+3
regex
source share
1 answer

for the nth match, use this pattern (?:.*?\$[0-9.]+){XX}.*?(\$[0-9.]+)
where XX = n-1

Example for the third match

+3
source share

All Articles