1

how can I extract only numbers from text string. Many times appear C{d}{d}{d}... which has to be removed. Only persist numbers.

text=['C1412DRE, New York 2695','Direction 12','Main Street 6254 C13D']
re.sub('[a-zA-Z]', '', str(text))


Desired output:
[2695,12,6254]
1
  • 2
    Try (?<!\S)\d+(?!\w) or use a word boundary \b\d+\b Commented Jul 23, 2019 at 15:36

2 Answers 2

3

Rather than trying to strip away all alpha characters, I would rather search for all standalone numbers. Here is one option, using re.findall with the regex pattern \b\d+\b:

text = ['C1412DRE, New York 2695','Direction 12','Main Street 6254 C13D']
inp = ' '.join(text)
matches = re.findall(r'\b\d+\b', inp)
print(matches)

['2695', '12', '6254']

One possible flaw in my logic is that I join together your list of strings into a single string, separated by space. This is required because re.findall expects a single string for searching. But, since the regex pattern is only looking for numbers already separated by a word boundary, joining by space should not introduce any side effects (I think).

Sign up to request clarification or add additional context in comments.

Comments

1

without regexp

text = ['C1412DRE, New York 2695','Direction 12','Main Street 6254 C13D']
str = ' '.join(text)
[int(s) for s in str.split() if s.isdigit()]
[2695, 12, 6254]

with regexp:

import re
re.findall(r'\b\d+\b', str)                                                                                                                                                                                                                          
['2695', '12', '6254']

and convert them to digits

[int(s) for s in re.findall(r'\b\d+\b', str)]
[2695, 12, 6254]

https://docs.python.org/3/library/re.html

The great playgroud where you may try your regexp with codegen: https://regex101.com/r/4kUHhq/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.