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?
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.
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.
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 "(" .
Most library implementations of regular expressions use a backtracking algorithm that can take an exponential amount of time on some inputs.
You can use this regex to pick N
th 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 digitRegEx Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With