python - How to find a pair of numbers between parentheses using a regular expression? -
i have following string text / numbers in it. there ()
2 numbers in between. these 2 numbers need extracted. string looks this:
s = 'sadfdaf dsf4as d a4d34s ddfd (54.4433,-112.3554) a45 6sd 6f8 asdf'
i need regular expression solving that. pseudo code this
search
s
(
, check if number next charextract numbers until
,
- extract second number until
)
i found following solution stackoverflow
print re.findall("[-+]?\d+[\.]?\d*[ee]?[-+]?\d*", schooladdressstring)
which returns: ['4', '4', '34', '54.4433', '-112.3554', '45', '6', '6', '8']
so need have expression consider numbers between ()
like^(
, $(
.
how done exactly?
you use regex capture elements between brackets, , parse these using .split(',')
, float
parse them floats. like:
for match in re.findall(r'(?<=\().*?(?=\))',schooladdressstring): a,b = map(float,match.split(',')) # , b, example print([a,b])
this prints:
>>> match in re.findall(r'(?<=\().*?(?=\))',schooladdressstring): ... a,b = map(float,match.split(',')) ... # , b, example ... print([a,b]) ... [54.4433, -112.3554]
furthermore here parse float
. therefore think parsing less error prone: there more patterns can parsed, , parsing done correctly.
the result of map(..)
list. in case there can arbitrary number of values between brackets, can use values = map(..)
, process elements in values
.
float pattern
the pattern float(..)
constructor can parse described in the documentation:
sign ::= "+" | "-" infinity ::= "infinity" | "inf" nan ::= "nan" numeric_value ::= floatnumber | infinity | nan numeric_string ::= [sign] numeric_value floatnumber ::= pointfloat | exponentfloat pointfloat ::= [digitpart] fraction | digitpart "." exponentfloat ::= (digitpart | pointfloat) exponent digitpart ::= digit (["_"] digit)* fraction ::= "." digitpart exponent ::= ("e" | "e") ["+" | "-"] digitpart digit ::= "0"..."9"
so "added" value of using constructor underscores allowed (to separate groups of digits), , furthermore values infinity
, inf
, nan
allowed.
Comments
Post a Comment