Is there a way to match a complete string before python3.4(as they introduced fullmatch() method here.)
For eg. If i have a string '12.345' and If i want to check for float with no exponential and i use the pattern: r'-?(?:\d+())?(?:\.\d+())?'
. But this pattern also works for '12.345abc'.
How can i make re to not match second string '12.345abc'?
Thanks!
Asked
Active
Viewed 2,206 times
1

mrig
- 382
- 1
- 4
- 21
-
1[Anchors](https://docs.python.org/2/library/re.html#regular-expression-syntax) are your friend: `r'^-?(?:\d+())?(?:\.\d+())?$'` – dhke Apr 12 '17 at 20:46
-
thanks! works. and already answered as well :) – mrig Apr 12 '17 at 20:51
1 Answers
1
You might want to use anchors in combination with filter()
and lambda()
:
import re
strings = ['12.345', '12.345abc']
rx = re.compile(r'^\d+(\.\d+)?$')
numbers = list(filter(lambda x: rx.match(x), strings))
print(numbers)
# ['12.345']
This makes sure no rubbish is matched afterwards.

Jan
- 42,290
- 8
- 54
- 79