Custom Regex Word Borders in JavaScript

We have a JS script where we evaluate the calculations, but we have a problem with leading zeros. JS treats numbers with leading zeros as octal numbers. Therefore, we used a regular expression 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 at https://regex101.com/r/mL3jS8/2 )

A regular expression works fine, but not with numbers, including ',' or '.'. This is considered as a word boundary, and zeros are also removed.

We found a solution using negative lookbehinds / lookforwards, but JS does not support this.

It hurts, our knowledge of regular expressions ends here :( and we do not like google.

Who can help us?

+5
source share
2 answers

If you understand 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 at regex101.com .

+4
source

If I figured out what you want, this is my solution:

 var txt001 = "102".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt002 = "1,03".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt003 = "1.03".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt004 = "004".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt005 = "05".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt006 = "06+07".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt007 = "08/09".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt008 = "010,10,01".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt009 = "00,01".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt010 = "0001".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt011 = "01*01".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt012 = "010,0".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt013 = "0,0000001".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); var txt014 = "5/0".replace(/(^|\+|\-|\*|\/)0+(\d)/g, "$1$2"); 

And the result

 102 1,03 1.03 4 5 6+7 8/9 10,10,01 0,01 1 1*1 10,0 0,0000001 5/0 
0
source

Source: https://habr.com/ru/post/1236030/


All Articles