Finding the nth occurrence of a number using regex

蓝咒 提交于 2019-12-10 15:00:20

问题


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}.

What I am trying to do is pick out the number out of a string like: Red,12,Green,5,Blue,6

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?


回答1:


You can use this regex to pick Nth number:

(?:\D*(\d+)){2}

Replace 2 by any number you want. Your number is available in captured group #1

  • \D matches any non-digit
  • \d matches a digit

RegEx Demo



来源:https://stackoverflow.com/questions/37751545/finding-the-nth-occurrence-of-a-number-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!