3

In a string I want all the decimal numbers, i.e something like 23.45.

However the condition is that the number should be between spaces and not like length23.455 or 23.45is the length.

So the decimal in the string length 23.455 is acceptable.

If there is a number like 23.45.34 it should be ignored, i.e neither 23.45 nor 45.34 should be displayed.

Need a regex pattern that finds all the matches in Python.

For example, consider the following string:

"6.5 from1.2 .34 12.34 13.44.55 12.34.55.66 11.43 12.3 12. 12.78~ fdasfdashf 66.8987"

I need a code like the following

import re
input_str = "6.5 from1.2 .34 12.34 13.44.55 12.34.55.66 11.43 12.3 12. 12.78~ fdasfdashf 66.8987"
print(re.findall(<regex>, input_str)) # replace <regex> with appropriate regex.

The output generated should be :

6.5, 12.34, 11.43, 12.3, 66.8987
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Dhana
  • 505
  • 1
  • 8
  • 27

1 Answers1

3

You need to check if the number is NOT preceded or followed by a non-whitespace character, you can achieve that with look-arounds (?<!\S) and (?!\S). The regex to match a float with obligatory integer and decimal part is trivial: \d+\.\d+.

import re
input_str = "6.5 from1.2 .34 12.34 13.44.55 12.34.55.66 11.43 12.3 12. 12.78~ fdasfdashf 66.8987"
print(re.findall(r"(?<!\S)\d+\.\d+(?!\S)", input_str))

See IDEONE demo

Result: ['6.5', '12.34', '11.43', '12.3', '66.8987']

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563