繁体   English   中英

如何使用 JS String.replace 并使用 RegEx 替换为括号组的一部分

[英]How do I use JS String.replace and replace with a part of a bracket group using RegEx

我有这个代码:

string
  .replace(/^1[xyz]/g, "$1")
  .replace(/-1[xyz]/g, "-$1")
  .replace(/ 1[xyz]/g, " $1");

其中string是一个数学表达式。 我希望将$1替换为 x、y 或 z,具体取决于它在括号中匹配的字母。 这应该替换字符串中的所有出现。 如何使其正确替换?

例子:

  • 1xx
  • -1x-x
  • 5x + 1y5x + y
  • 1x - 1zx - z
  • 11x + 21y11x + 21y (只替换1,不替换11、21等)

你可能会使用

\b1([xyz])
  • \b1一个词的边界,然后匹配 1
  • ([xyz])捕获组 1,匹配x yz之一

在替换使用组 1 中。

正则表达式演示

 const pattern = /\b1([xyz])/g; [ "1x", "-1x", "5x + 1y", "1x - 1z", "11x + 21y" ].forEach(s => console.log(s + " => " + s.replace(pattern, "$1")));

暂无
暂无

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

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