使用正则表达式查找数字的第n次出现 [英] Finding the nth occurrence of a number using regex
问题描述
我正在尝试编写一个正则表达式,它可以找到第n个出现的数字匹配项(其中N是可以在for循环中递增的数字)。我可以让正则表达式成功匹配一个数字,但不能使其与序列中的特定数字匹配。我使用的正则表达式是([[0-9] +){2}
。
I am trying to write a regex that can find the nth occurrence of a number match (where N is a number that can increment in a for loop). I can get the regex to successfully match a number, but I can't get it to match a specific number in the sequence. The regex I used is ([0-9]+){2}
.
我要尝试的操作要做的就是从一个字符串中选出数字:Red,12,Green,5,Blue,6
What I am trying to do is pick out the number out of a string like: Red,12,Green,5,Blue,6
使用可以提取的正则表达式,然后是12、2 ,然后是3。我希望正则表达式的 {n}
部分可以完成此操作,但是例如当我将该数字设置为2而不是选择数字5时如预期的那样,它选择了12中的2,当我将数字设置为3时,它根本找不到匹配项。谁能提供我做错事情的任何见解?
Using a regex that can pick out, 12 then, 2, then 3. I was hoping the {n}
part of the regex could accomplish this, but when I set that number to 2 for instance, instead of picking out the number 5 as expected, it picks up the 2 in 12, and when I set the number to 3, it is unable to find a match at all. Could anyone provide any insight into what I am doing wrong?
推荐答案
您可以使用此正则表达式选择 N
个数字:
You can use this regex to pick N
th number:
(?:\D*(\d+)){2}
将 2
替换为您想要的任何数字。您的电话号码在捕获的#1组中可用
Replace 2
by any number you want. Your number is available in captured group #1
-
\D
与任何非-digit -
\d
匹配数字
\D
matches any non-digit\d
matches a digit
这篇关于使用正则表达式查找数字的第n次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!