简体   繁体   English

替换功能仅会替换第二个正则表达式匹配项

[英]Replace function does only replace every second regex match

I would like to use regex in javascript to put a zero before every number that has exactly one digit. 我想在javascript中使用正则表达式在每个具有一位数字的数字前放置零。

When i debug the code in the chrome debugger it gives me a strange result where only every second match the zero is put. 当我在chrome调试器中调试代码时,它给了我一个奇怪的结果,即每秒仅匹配零。

My regex 我的正则表达式

"3-3-7-3-9-8-10-5".replace(/(\-|^)(\d)(\-|$)/g, "$10$2$3");

And the result i get from this 而我从中得到的结果

"03-3-07-3-09-8-10-05"

Thanks for the help 谢谢您的帮助

Use word boundaries, 使用单词边界

(\b\d\b)

Replacement string: 替换字符串:

0$1

DEMO 演示

> "3-3-7-3-9-8-10-5".replace(/(\b\d\b)/g, "0$1")
'03-03-07-03-09-08-10-05'

Explanation: 说明:

  • ( starting point of first Capturing group. (第一个捕获组的起点。
  • \\b Matches between a word character and a non word character. \\b在单词字符和非单词字符之间匹配。
  • \\d Matches a single digit. \\d匹配一位数字。
  • \\b Matches between a word character and a non word character. \\b在单词字符和非单词字符之间匹配。
  • ) End of first Capturing group. )第一个捕获组的结尾。

You can use this better lookahead based regex to prefix 0 before every single digit number: 您可以使用此更好的基于前瞻的正则表达式在每个数字前添加前缀0

"3-3-7-3-9-8-10-5".replace(/\b(\d)\b(?=-|$)/g, "0$1");
//=> "03-03-07-03-09-08-10-05"

Reason why you're getting alternate prefixes in your regex: 为什么在正则表达式中获得备用前缀的原因:

"3-3-7-3-9-8-10-5".replace(/(\-|^)(\d)(\-|$)/g, "$10$2$3");

is that rather than looking ahead you're actually matching hyphen after the digit. 而不是向前看,实际上是在数字后面匹配连字符。 Once a hyphen has been matched it is not matched again since internal regex pointer has already moved ahead. 连字符匹配后,将不再匹配,因为内部正则表达式指针已经向前移动。

使用正向前瞻来查看一位数字:

"3-3-7-3-9-8-10-5".replace(/(?=\b\d\b)/g, "0");

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

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