Reputation: 1
I have a string thath goes like that:
<123, 321>
the range of the numbers can be between 0
to 999
.
I need to insert those coordinates as fast as possible into two variables, so i thought about regex. I've already splitted the string to two parts and now i need to isolate the integer from all the other characters. I've tried this pattern:
^-?[0-9]+$
but the output is:
[]
any help? :)
Upvotes: 0
Views: 104
Reputation: 26667
All you need to do is to get rid of the anchors( ^
and $
)
>>> import re
>>> string = "<123, 321>"
>>> re.findall(r"-?[0-9]+", string)
['123', '321']
>>>
Note ^
$
Anchors at the start and end of patterns -?[0-9]+
ensures that the string consists only of digits.
That is the regex engine attempts to match the pattern from the start of the string, ^
using -?[0-9]+
till the end of the string $
. But it fails because <
cannot be matched by -?[0-9]+
Where as the re.findall will find all substrings that match the pattern -?[0-9]+
, that is the digits.
Upvotes: 1
Reputation: 25329
If your strings follow the same format <123, 321>
then this should be a little bit faster than regex approach
def str_translate(s):
return s.translate(None, " <>").split(',')
In [52]: str_translate("<123, 321>")
Out[52]: ['123', '321']
Upvotes: 2
Reputation: 11113
"^-?[0-9]+$"
will only match a string that contains a number and nothing else.
You want to match a group and the extract that group:
>>> pattern = re.compile("(-?[0-9]+)")
>>> pattern.findall("<123, 321>")
['123', '321']
Upvotes: 0