I would extract all the numbers contained in a string. Which is the better suited for the purpose, regular expressions or the isdigit()
method?
Example:
To catch different patterns it is helpful to query with different patterns.
'[\d]+[.,\d]+'
'[\d]*[.][\d]+'
'[\d]+'
(Note: Put complex patterns first else simple patterns will return chunks of the complex catch instead of the complex catch returning the full catch).
p = '[\d]+[.,\d]+|[\d]*[.][\d]+|[\d]+'
Below, we'll confirm a pattern is present with re.search()
, then return an iterable list of catches. Finally, we'll print each catch using bracket notation to subselect the match object return value from the match object.
s = 'he33llo 42 I\'m a 32 string 30 444.4 12,001'
if re.search(p, s) is not None:
for catch in re.finditer(p, s):
print(catch[0]) # catch is a match object
Returns:
33
42
32
30
444.4
12,001