Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

regex - regular expression capture nth match

Is there any way to, using regular expression, return the nth occurrence? I did search the forums and only found solution that goes beyond regular expression itself (i.e. needs support from the programming language).

Example: Regex:

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

Input:

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

I'd need to extract the first one (which is 25.74). Later on I might need to extract the third one (which is 54.32).

My regex is currently matching all occurrences. I could retrieve the nth element after matches but my question is: is it possible to do it via regular expression only (i.e. the regular expression will return only the nth element I want)?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Example for 3rd match


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...