Erwin
Erwin

Reputation: 381

How to remove pattern of number with a specific character and keep only the number?

I am new to python with regex and I have a question to remove the pattern of string contain numbers with a specific character for example we have a pattern like this: 1234" with a special character " and I want to keep only 1234 by removing the " from those numbers.

Here is what I detect for that pattern:

s = re.sub(r'[0-9]+\"','',s)

The question is how can I put in ' ' to get the numbers I want back if we keep ' ' sure it will remove the number also not only the ".

Desire result:

s = 1234

Thank you so much for your help.

Upvotes: 0

Views: 373

Answers (2)

Austin
Austin

Reputation: 26039

Get the matched pattern and use it (while specifically for your case s[:-1] also works):

re.sub(r'([0-9]+)\"','\\1',s)

Upvotes: 1

HARSH MITTAL
HARSH MITTAL

Reputation: 760

import re

a = "1234 extra text"
numbers = re.findall('[0-9]+', a)
s = int(numbers[0])
print("s = ",s)

Output:

s = 12345

You will get numbers as a list. If there are multiple int vales separated by characters they will be stored in the list. eg:

a = "1234 34"
numbers = re.findall('[0-9]+', a)
print(numbers)

Output:

['1234','34']

Upvotes: 0

Related Questions