-1

Giving this string:

numbers 1 2 10 20

where the amount of numbers might be 1 or more, how can I get only the numbers? (i.e expression that would return:

[1, 2, 10, 20]

My closest try was:

re.findall(r'numbers (\d +)', 'numbers 1 2 10 20')
>>> ['1 ']

Edit:

The case above is not telling the whole story so I will explain a bit more.

I have a list of strings, and I need to first figure out whether one of them is matching the pattern number X Y Z as explained above. If such a string is indeed in that list I want to extract from it only the numbers.

I can do it in multiple steps but I wonder If I can use regex here to get what I want with a one-liner.

Examples:

Let's assum that the function func1(list) is our magic function that do all I requires.

l1 = ['letters a b c', 'numbers 1 12 6']
l2 = ['animalas dog cat', 'colors red blue']

>>> func1(l1)
OUT: [1, 12, 6]

>>> func2(l1)
OUT: []
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
Andy Thomas
  • 1,219
  • 3
  • 19
  • 33

1 Answers1

-1
strr = "numbers 1 2 10 20"

Uhm:

print(''.join([n for n in strr if n.isdigit()]))

OR

print([int(s) for s in re.findall(r'\b\d+\b', strr)])

OR

import re
print(map(int, re.findall('\d+', strr)))

OUTPUT:

[1, 2, 10, 20]

Based on OP's EDIT:

You need to match the string first before you fetch all the digits out of it:

if re.match("numbers .*"+ r'\b\d+\b', strr):
    print("String pattern matched, Now extracting..")

Hence:

import re

def func1(strrList):
        for strr in strrList:        
            if re.match("numbers .*"+ r'\b\d+\b', strr):
                print("String pattern matched, Now extracting..")
                print(map(int, re.findall('\d+', strr)))
            else:
                print("String pattern failed to match.")


l1 = ['letters a b c', 'numbers 1 12 6']
l2 = ['animalas dog cat', 'colors red blue']

func1(l1)

OUTPUT:

String pattern failed to match.

String pattern matched, Now extracting..

[1, 12, 6]

Community
  • 1
  • 1
DirtyBit
  • 16,613
  • 4
  • 34
  • 55