Home > OS >  Get peace of number using Regex in Python
Get peace of number using Regex in Python

Time:03-31

I´m trying to get a part of number using Regex in Python, I want to collect the sequence of numbers after 0 (zero) number, like this:

S_9900002127
S_9900000719
S_9900008012

So, in this example above I want to get: 2127, 719 and 8012, and I have done the Regex:

r'(_9(\d*)[.^0](\d*))' 

and get the second group of Regex: [2], but the result is: 2127, 719 and 12.

Look that the third one ignore the number 8 because the 0 (zero).

Could someone help me to get the correct result 2127, 719 and 8012 ???

CodePudding user response:

You can use

import re
text = r"""S_9900002127
S_9900000719
S_9900008012"""
print( re.findall(r'0 ([1-9]\d*)$', text, re.M) )
# => ['2127', '719', '8012']

See the Python demo and the regex demo. Details:

  • 0 - one or more 0s
  • ([1-9]\d*) - Group 1: a non-zero digit and then zero or more digits
  • $ - end of a line.
  • Related