簡體   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