Skip to content
Advertisement

Add leading zero to numeric strings containing decimal value if no leading number

I have about 200 lines in text file

values can be like

JavaScript

And I am looking specific regex pattern for replace .number like ‘.1’ or ‘.8’

JavaScript

It’s working, but for value 1.5 it’s output is 10.5 and that’s wrong.

Advertisement

Answer

If all of your values are float or integer expressions, then you can use bluntly use “start of string followed by literal dot”: (Demo)

JavaScript

If you need to make sure that the dot at the start of the string is followed by a digit, you could add a lookahead: (Demo)

JavaScript

Either way, you don’t need to leverage any capture groups or backreferences.

It may be useful for you to know that preg_replace() will happily iterate your array on its own — no additional loop needs to be written.


If you’d like to directly manipulate your txt file, just add a m pattern modifier so that ^ means the start of each line. (Demo)

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement