Harvey
Harvey

Reputation: 145

How to use regex to replace string with fixed size of char

Let's say I have the following text :

TimeOut_BN:1292 ms
TimeOut_BN:130 ms
TimeOut_BN:1313 ms
TimeOut_BN:1329 ms
TimeOut_BN:19 ms
TimeOut_BN:5 ms
TimeOut_BN:154 ms

I want to replace all numbers with formatted numbers (exactly 4 chars)

TimeOut_BN:1292 ms
TimeOut_BN: 130 ms
TimeOut_BN:1313 ms
TimeOut_BN:1329 ms
TimeOut_BN:  19 ms
TimeOut_BN:   5 ms
TimeOut_BN: 154 ms

I use the following regex to find the numbers

BN:(.*)\sms

But I don't know how to tell "Replace with exactly 4 chars".

Is there a way to do this ?


@revo It looks great, the idea is good, but when I tested it on regex101 I got :

TimeOut_BN:(?{1} 1292)(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} )(?{2}  130)(?{3}   ) ms
TimeOut_BN:(?{1} 1313)(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} 1329)(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} )(?{2}  )(?{3}   19) ms
TimeOut_BN:(?{1} )(?{2}  )(?{3}   ) ms
TimeOut_BN:(?{1} )(?{2}  154)(?{3}   ) ms

Upvotes: 0

Views: 310

Answers (1)

revo
revo

Reputation: 48711

You may be able to do it in one step, first try to find:

^TimeOut_BN:\K(?:(\d{3})|(\d\d)|(\d))\b

then replace it with

(?{1} $1)(?{2}  $2)(?{3}   $3)

Upvotes: 4

Related Questions