3

This is my string

data = 'hs122 125 &55,58, 25'

Expected Result: [122, 125, 55, 58, 25]

Try1:

data = 'hs122 125 &55,58, 25'
s = re.search(r"\d+(\.\d+)?", data)
print(s.group(0))

Output: 122

Try2:

data = 'hs122 125 &55,58, 25'
s = [int(s) for s in data.split() if s.isdigit()]
print(s)

Output: [125, 25]

Try3:

p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
data = 'hs122 125 &55,58, 25'
numbers = []
if re.search(p, data) is not None:
    for catch in re.finditer(p, data):
        numbers.append(catch[0])
print(numbers)

Output: ['122', '125', '55,58,', '25']

2 Answers 2

2

try this

import re
data = 'hs122 125 &55,58, 25'

results = list(map(int, re.findall(r'\d+', data)))
print(results)
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply use \d+ with findall:

re.findall(r'\d+', 'hs122 125 &55,58, 25')
# ['122', '125', '55', '58', '25']

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.