-1

I seen Q&A like this and this but I still have a problem.

What I want is to get a string that might contain non-digits characters, and I want to only extract 2 numbers from that string. So, if my string is 12 ds d21a I want to extract ['12', '21'].

I tried using:

import re
non_decimal = re.compile(r'[^\d.]+')
non_decimal.sub("",input())

and fed this string 12 123124kjsv dsaf31rn. The result was 12123124 which is nice, but I want the non-digit characters to separate the numbers.

Next I tried to add split - non_decimal.sub("",input().split()). Didn't help.

How can I do that (assuming there is way that does not include scanning the whole string, iterating over it and extracting the digits "manually")?

For more clarification, this is what I want to achieve, in C.

Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124

3 Answers3

6

You want to use re.findall() method in this case -

input_ = '12 123124kjsv dsaf31rn' 
non_decimal = re.findall(r'[\d.]+', input_)

Output -

['12', '123124', '31']
Vivek Kalyanarangan
  • 8,951
  • 1
  • 23
  • 42
2

@Vivek answer will solve your issue.

Here is another approach , Just an opinion :

import re
pattern=r'[0-9]+'
string_1="""12 ds  d21a
12 123124kjsv dsaf31rn"""

match=re.finditer(pattern,string_1)
print([find.group() for find in match])

output:

['12', '21', '12', '123124', '31']
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88
1

If all you want to extract are positive integers, do this :

>>> string = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(x) for x in string.split() if x.isdigit()]
[23, 11, 2]

Then if you want more conditions and want to include scientific notations too:

import re

# Format is [(<string>, <expected output>), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
       ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
      ('hello X42 I\'m a Y-32.35 string Z30',
       ['42', '-32.35', '30']),
      ('he33llo 42 I\'m a 32 string -30', 
       ['33', '42', '32', '-30']),
      ('h3110 23 cat 444.4 rabbit 11 2 dog', 
       ['3110', '23', '444.4', '11', '2']),
      ('hello 12 hi 89', 
       ['12', '89']),
      ('4', 
       ['4']),
      ('I like 74,600 commas not,500', 
       ['74,600', '500']),
      ('I like bad math 1+2=.001', 
       ['1', '+2', '.001'])]

for s, r in ss:
    rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
    if rr == r:
        print('GOOD')
    else:
        print('WRONG', rr, 'should be', r)

Taken from this.

Shivansh Jagga
  • 1,541
  • 1
  • 15
  • 24