[英]How do I replace last part of string using string.replace() Javascript / Node.js
[英]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,具體取決於它在括號中匹配的字母。 這應該替換字符串中的所有出現。 如何使其正確替換?
例子:
1x
→ x
-1x
→ -x
5x + 1y
→ 5x + y
1x - 1z
→ x - z
11x + 21y
→ 11x + 21y
(只替換1,不替換11、21等)你可能會使用
\b1([xyz])
\b1
一個詞的邊界,然后匹配 1([xyz])
捕獲組 1,匹配x
y
或z
之一在替換使用組 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.