简体   繁体   English

JavaScript中的正则表达式自定义词边界

[英]Regex Custom Word Boundaries in JavaScript

We have some JS script where we evaluate calculations, but we have an issue with leading zeros. 我们有一些JS脚本来评估计算,但是我们遇到了前导零的问题。 JS treats the numbers with leading zeros as octal numbers. JS将带有前导零的数字视为八进制数。 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 ) (也可在线访问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. 我们找到了一个使用负面lookbehinds / lookforwards的解决方案,但JS并不支持。

Painfully, our regex knowledge ends here :( and google doesn't like us. 痛苦地,我们的正则表达式知识在这里结束:(和谷歌不喜欢我们。

Anyone who can help us? 谁可以帮助我们?

If I understood you correctly, the following should work: 如果我理解正确,以下应该有效:

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

Replace the match with $1$2 . $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 . 在regex101.com上测试它。

If i understood 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 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM