I want to extract and print a variable number '-34.99' from the string:
myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09"
The values in the string will change. How can I do it with the regular expression in Python?
Thanks in advance
Non-regex solution is:
myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09"
print myString.split("/")[1]
Test this code here.
One of regex solutions would be:
import re
myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09"
print re.search(r'(?<=\/)[+-]?\d+(?:\.\d+)?', myString).group()
Test this code here.
Explanation:
(?<=\/)[+-]?\d+(?:\.\d+)?
└──┬──┘└─┬─┘└┬┘└───┬────┘
│ │ │ │
│ │ │ └ optional period with one or more trailing digits
│ │ │
│ │ └ one or more digits
│ │
│ └ optional + or -
│
└ leading slash before match
For something like this, re.findall works great:
>>> import re
>>> myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09"
>>> re.findall(r'([+-]?\d+\.\d+)',myString)
['-35.00', '-34.99', '-34.00', '0.09']
You can get the floats directly with a list comprehension:
>>> [float(f) for f in re.findall(r'([+-]?\d+\.\d+)',myString)]
[-35.0, -34.99, -34.0, 0.09]
Or the second one like this:
>>> re.findall(r'([+-]?\d+\.\d+)',myString)[1]
'-34.99'
The question will be how big a range of textual floating points will you accept? Some with no decimal points? Exponents?
>>> myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09/5/1.0e6/1e-6"
Ouch! -- this is getting harder with a regex.
You actually may be better off just using Python's string ops:
>>> ''.join([s for s in myString.split() if '/' in s]).split('/')
['-35.00', '-34.99', '-34.00', '0.09', '5', '1.0e6', '1e-6']
You can get the nth one same way:
>>> n=2
>>> ''.join([s for s in myString.split() if '/' in s]).split('/')[n]
'-34.00'
Then all the weird cases work without a harder regex:
>>> map(float,''.join([s for s in myString.split() if '/' in s]).split('/'))
[-35.0, -34.99, -34.0, 0.09, 5.0, 1000000.0, 1e-06]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With