Sublime Forum

Add a digit with regex

#1

Hi everyone,

I have a file with lines which look like this:

2019/9/24, 15:02:08.8
2019/9/24, 15:02:08.9
2019/9/24, 15:02:08.10
2019/9/24, 15:02:08.11
2019/9/24, 15:02:08.111
2019/9/24, 15:02:08.112

I need to add leading zeroes to the last numbers (milliseconds,the ones after the period) where they don’t have three digits, i.e. 08.008, 08.009, 08.010, 08.011 etc.

I imagine this can be done with regex, but I’m simply an amateur when it comes to regex :frowning:

I’d appreciate any help!

0 Likes

#2

I got a reply at stackoverflow. For those interested:

You can do it in two stages, firstly where 2 digits, secondly where only 1 digit:

Find > Replace > (ensure regex is turned on - button looks like .* )

Find: (\d{2}:\d{2}:\d{2}).(\d{2},)
Replace: $1.0$2

Then

Find: (\d{2}:\d{2}:\d{2}).(\d{1},)
Replace: $1.00$2

Brief explanation

In the find: \d is a number, {2} means exactly 2, brackets capture a group
In the replace: $1 is the first group, .0 replaces the . with .0 , $2 is the second group

0 Likes

#3

Looks like I rejoiced too quickly. I tried it on a quite large file, and it worked beautifully. Since then I’ve been trying it on a file with the same layout, but smaller (less lines) but I keep on getting a message that “the complexity of matching the regular expression exceeds predefined bounds. Try refactoring the regular expression to make to make each choice made by the state machine unambigious.”

Any help appreciated!

0 Likes

#4

Those regex don’t match for me on that input unless I remove the last , in each one (before the last ) character).

In any case, you might have more luck by adding a $ to the end of the regex to anchor it at the end of the line. That might stop it from looking too far ahead.

0 Likes