Regex: Match decimal numerals with no digits before decimal point

99 Views Asked by At

I am trying to match decimal numerals with no digits before the decimal point in a string using regex. For example, I have the strings:

The dimensions of the object-1 is: 1.4 meters wide, .5 meters long, 5.6 meters high
The dimensions of the object-2 is: .8 meters wide, .11 meters long, 0.6 meters high

I want to capture only the decimal numbers without integer digits and prefix leading zeros to them. So my final desired output will be:

The dimensions of the object-1 is: 1.4 meters wide, 0.5 meters long, 5.6 meters high
The dimensions of the object-2 is: 0.8 meters wide, 0.11 meters long, 0.6 meters high

This is what I have tried so far:

(\d+)?\.(\d+)

This expression is capturing all the decimal numbers such as: 1.4, .5, 5.6, .8, .11, 0.6.

But I need to capture only decimal numbers without integer digits: .5, .8, .11.

2

There are 2 best solutions below

0
Sweet Sheep On

Use a negative lookbehind: (?<!\d)(\.\d+)

1
Amila Senadheera On

You can do a regex substitution with negative look behind for a digit.

Regex - (?<!\d)(\.\d+)

  • (?<!\d) - Checks that no digit before the regex
  • (\.\d+) - Captures the dot and one or more consecutive digits

Substitution - 0\1

  • 0 - Adds a single zero for the capture
  • \1 - Back reference to the capture group which is the float starts with a dot

Regex101 Demo for python regex flavour

Python code sample

import re

string = "The dimensions of the object-1 is: 1.4 meters wide, .5 meters long, 5.6 meters high \nThe dimensions of the object-2 is: .8 meters wide, .11 meters long, 0.6 meters high"
pattern = r"(?<!\d)(\.\d+)"

match = re.search(pattern, string)
new_string = re.sub(pattern, "Number: 0\\1", string)

print(new_string)