Regex Behaving Weird When Finding Floating Point Strings
So doing this (in python 3.7.3): >>> from re import findall >>> s = '7.95 + 10 pieces' >>> findall(r'(\d*\.)?\d+', s) ['7.', ''] # Expected return: ['7
Solution 1:
As you guessed correctly, this has to do with capturing groups. According to the documentation for re.findall
:
If one or more groups are present in the pattern, return a list of groups
Therefore, you need to make all your groups ()
non-capturing using the (?:)
specifier. If there are no captured groups, it will return the entire match:
>>> pattern = r'(?:\d*\.)?\d+'>>> findall(pattern, s)
['7.95', '10']
Post a Comment for "Regex Behaving Weird When Finding Floating Point Strings"