There is a string consisting several numbers, for example:
12.03 5.897 7.10.74 0.103 12.05 6.4.1 8.98
I want to use Python regular expression to output only those numbers with ONLY single dot (.), such as "12.03" and "5.897", not "7.10.74" and "6.4.1".
I know this is a trivial question without regex, I just want to solve this with regex. But I really couldn't figure out how to solve this with regex. Can somebody help me?
If you want a pure regex solution then use lookarounds:
>>> s = "12.03 5.897 7.10.74 0.103 12.05 6.4.1 8.98"
>>> print re.findall(r'(?<!\.)\b\d+\.\d+\b(?!\.)', s)
['12.03', '5.897', '0.103', '12.05', '8.98']
RegEx Demo
(?<!\.) is negative lookbehind to assert failure when previous char is DOT.(?!\.) is negative lookahead to assert failure when next char is DOT.\b is word boundary which is required on both sides to make sure we match full decimal numberUse (?<=\s)\d*\.\d*(?=\s|$)|^\d*\.\d*(?=\s|$):
import re
re.findall(r'(?<=\s)\d*\.\d*(?=\s|$)|^\d*\.\d*(?=\s|$)', s)
# ['12.03', '5.897', '0.103', '12.05', '8.98']
(?<=\s)\d*\.\d*(?=\s|$) or ^\d*\.\d*(?=\s|$) depending on whether the number is at the beginning of the string;\d*\.\d*(?=\s|$) matches a number with one dot followed by a space or the end of the string;Note: Can not use (?<=\s|^) to integrate both cases because the look-behind syntax does not support so;
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