Extracting a number from a string in Python with regex

I want to extract and print the variable number -34.99 from the line:

myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09" 

The values ​​in the row will be changed. How can I do this with regex in Python?

Thank you in advance

+4
source share
2 answers

Non-modal solution:

 myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09" print myString.split("/")[1] 

Check out this code here .


One solution to regular expressions:

 import re myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09" print re.search(r'(?<=\/)[+-]?\d+(?:\.\d+)?', myString).group() 

Check out this code here .

Explanation:

 (?<=\/)[+-]?\d+(?:\.\d+)? β””β”€β”€β”¬β”€β”€β”˜β””β”€β”¬β”€β”˜β””β”¬β”˜β””β”€β”€β”€β”¬β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”” optional period with one or more trailing digits β”‚ β”‚ β”‚ β”‚ β”‚ β”” one or more digits β”‚ β”‚ β”‚ β”” optional + or - β”‚ β”” leading slash before match 
+13
source

For something like this, re.findall works fine:

 >>> 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 floats directly with a list:

 >>> [float(f) for f in re.findall(r'([+-]?\d+\.\d+)',myString)] [-35.0, -34.99, -34.0, 0.09] 

Or the second one is:

 >>> re.findall(r'([+-]?\d+\.\d+)',myString)[1] '-34.99' 

The question will be, how large a range of text floating points will you accept? Some without decimal points? Exhibitors?

 >>> myString = "Test1 [cm]: -35.00/-34.99/-34.00/0.09/5/1.0e6/1e-6" 

Oh! - it gets harder with regex.

Actually, you might be better off just using the python string commands:

 >>> ''.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 nth the 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 more complex regular expression:

 >>> 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] 
+1
source

All Articles