Reputation: 3
I used regular expression in python2.7 to match the number in a string but I can't match a single number in my expression, here are my code
import re
import cv2
s = '858 1790 -156.25 2'
re_matchData = re.compile(r'\-?\d{1,10}\.?\d{1,10}')
data = re.findall(re_matchData, s)
print data
and then print:
['858', '1790', '-156.25']
but when I change expression from
re_matchData = re.compile(r'\-?\d{1,10}\.?\d{1,10}')
to
re_matchData = re.compile(r'\-?\d{0,10}\.?\d{1,10}')
then print:
['858', '1790', '-156.25', '2']
is there any confuses between d{1, 10} and d{0,10} ? If I did wrong, how to correct it ? Thanks for checking my question !
Upvotes: 0
Views: 3802
Reputation: 6371
I would rather do as follows:
import re
s = '858 1790 -156.25 2'
re_matchData = re.compile(r'\-?\d{1,10}\.?\d{0,10}')
data = re_matchData.findall(s)
print data
Output:
['858', '1790', '-156.25', '2']
Upvotes: 0
Reputation: 16634
try this:
r'\-?\d{1,10}(?:\.\d{1,10})?'
use (?:)?
to make fractional part optional.
for r'\-?\d{0,10}\.?\d{1,10}'
, it is \.?\d{1,10}
who matched 2
.
Upvotes: 2
Reputation: 782407
The first \d{1,10}
matches from 1 to 10 digits, and the second \d{1,10}
also matches from 1 to 10 digits. In order for them both to match, you need at least 2 digits in your number, with an optional .
between them.
You should make the entire fraction optional, not just the .
.
r'\-?\d{1,10}(?:\.\d{1,10})?'
Upvotes: 1