Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Custom Word Boundaries in JavaScript

We have some JS script where we evaluate calculations, but we have an issue with leading zeros. JS treats the numbers with leading zeros as octal numbers. So we used a regex to remove all leading zeros:

\b0+(\d+)\b

Sample data:

102
1,03
1.03
004
05
06+07
08/09
010,10,01
00,01
0001
01*01
010,0
0,0000001
5/0

(also online on https://regex101.com/r/mL3jS8/2)

The regex works fine but not with numbers including ',' or '.'. This is seen as a word boundary and zeros are also removed.

We found a solution using negative lookbehinds/lookforwards, but JS doesn't support that.

Painfully, our regex knowledge ends here :( and google doesn't like us.

Anyone who can help us?

like image 997
Bjorn H Avatar asked Sep 26 '22 04:09

Bjorn H


1 Answers

If I understood you correctly, the following should work:

/(^|[^\d,.])0+(\d+)\b/

Replace the match with $1$2.

Explanation:

(        # Match and capture in group 1:
 ^       # Either the start-of-string anchor (in case the string starts with 0)
|        # or
 [^\d,.] # any character except ASCII digits, dots or commas.
)        # End of group 1.
0+       # Match one or more leading zeroes
(\d+)    # Match the number and capture it in group 2
\b       # Match the end of the number (a dot or comma could follow here)

Test it live on regex101.com.

like image 126
Tim Pietzcker Avatar answered Oct 05 '22 23:10

Tim Pietzcker