Home > Mobile >  Python regex remove nonnumeric chars in string
Python regex remove nonnumeric chars in string

Time:07-01

I have this code:

line = "Company Rx3M 123456789"
line = re.sub(r'[^a-zA-Z] $', '', line)
output: Company Rx3M

So, here number 3 is not being removed from "Company Rx3M" as it's a part of a name. I want it to be this way.

Now, I'm trying to get only 123456789 from the string without the number 3 within "Company Rx3M".

line = "Company Rx3M 123456789"
line = re.sub(r'[a-zA-Z]', '', line)

What I get:

output: 3 123456789

How to get only "123456789" out of the string?

CodePudding user response:

here is one way to do it

line = "Company Rx3M 123456789"
line = re.findall(r'\s(\d*)',  line)
int(line[1])
123456789

CodePudding user response:

Use positive lookahead searching for digits surrounded by word boundaries to make sure you find only numeric sequences (?=\b\d \b)\d .

  • Related