[英]Javascript regexp replace capturing
我正在嘗試在 Nodejs 應用程序中使用正則表達式。 我通常在 Python 中使用它,它似乎有一些差異。
這里的問題是:我有這個字符串\\newcommand{\\hello}{@replace}
,我想更換@replace
通過REPLACED
只有當我發現第二卷曲手鐲\\hello
的第一個花手鐲。 所以預期的結果是: \\newcommand{\\hello}{REPLACED}
我試試這個:
r = new RegExp('\\newcommand{\\hello}{(.*?)}');
s = '\\newcommand{\\hello}{@replace}';
s.replace(r, 'REPLACED');
但是什么都沒有被取代……有什么線索嗎?
r = new RegExp(/\\newcommand{\\hello}{@replace}/);
s = '\\newcommand{\\hello}{@replace}';
let a = s.replace(r, '\\newcommand{\\hello}{REPLACED}');
console.log(a)
輸出將是: "\\newcommand{\\hello}{REPLACED}"
我不確定我是否正確理解了這個問題。 這是你要找的嗎?
function replaceWith(myReplacement) {
var original = "\\newcommand{\\hello}{@replace}";
var regex = "{\\hello}{@replace}";
return original.replace(regex, `{\\hello}{${myReplacement}}`)
};
console.log(replaceWith("World"));
您根本不需要正則表達式來執行這種操作。 您可以簡單地在第一個參數中使用字符串:
s = '\\newcommand{\\hello}{@replace}';
s.replace('@replace', 'REPLACED'); // => "\newcommand{\hello}{REPLACED}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.