Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write python expression to filter out certain strings

Tags:

python

regex

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?

like image 419
Steve Yang Avatar asked Jul 04 '26 02:07

Steve Yang


2 Answers

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 number
like image 111
anubhava Avatar answered Jul 06 '26 17:07

anubhava


Use (?<=\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']
  • the patten matches either (?<=\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;

like image 33
Psidom Avatar answered Jul 06 '26 16:07

Psidom