0

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 !

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for checking my question, I ignored that the last part was an optional part in my expression
1

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})?'

1 Comment

Thanks! I didn't noticed that '.' have such useful feature in regular expression when I wrote the code.
0

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']

1 Comment

Thanks ! But I thought this style was a little be like a trick and not easy to read

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.