Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the nth occurrence of a number using regex

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?

like image 313
user3153443 Avatar asked Jun 10 '16 15:06

user3153443


People also ask

How do you find how many occurrences of a regex pattern were replaced in a string?

To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.

How do I match a number in regex?

The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

How do I match a pattern in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .

What algorithm is used with regex?

Most library implementations of regular expressions use a backtracking algorithm that can take an exponential amount of time on some inputs.


1 Answers

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

like image 162
anubhava Avatar answered Nov 07 '22 12:11

anubhava