正则表达式捕获第 n 个匹配项 [英] regular expression capture nth match
问题描述
有什么办法可以使用正则表达式返回第 n 次出现?我确实搜索了论坛,但只找到了超出正则表达式本身的解决方案(即需要编程语言的支持).
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).
示例:正则表达式:
(?:\$(\d+(?:,\d{3})*\.\d{2}))
输入:
thiscanbeanything$25.74thiscanbesomethingelse
alsowithnewlines$533.63thisonetoo$54.32plusthis$62.42thisneverends
我需要提取第一个(25.74).稍后我可能需要提取第三个(即 54.32).
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).
我的正则表达式目前正在匹配所有出现的情况.我可以在匹配后检索第 n 个元素,但我的问题是:是否可以仅通过正则表达式来完成(即正则表达式将仅返回我想要的第 n 个元素)?
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)?
谢谢!
推荐答案
对于第 n 个匹配使用此模式 (?:.*?\$[0-9.]+){XX}.*?(\$[0-9.]+)
其中 XX = n-1
for nth match use this pattern (?:.*?\$[0-9.]+){XX}.*?(\$[0-9.]+)
where XX = n-1
这篇关于正则表达式捕获第 n 个匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!