正则表达式用于替换文本失败



我正在尝试替换以下HTML中的heelo|paul,并将其替换为/heelo to paul/

<p>Dear sir&nbsp;&nbsp; {{heelo|Paul}}&nbsp; ,</p>n<p>I'm just testing please wait</p>n<p>yours faithfully,</p>n<p>&nbsp; 

这是我使用的正则表达式:

str.replace(/.*?{{|}}/g, "/$1 to $2/")

但它会产生错误的结果:

<p>Dear sir&nbsp;&nbsp; /$1 to $2/heelo|Paul/$1 to $2/&nbsp; ,</p>n<p>I'm just testing please wait</p>n<p>yours faithfully,</p>n<p>&nbsp

有什么想法吗?

您忘记了使用 转义|,也忘记将组添加到您想要的匹配项中。试试这个正则表达式:

(.*?{{)(.*?)|(.*?)(?=}})

这是一个有效的Javascript:

var myString = "<p>Dear sir&nbsp;&nbsp; {{heelo|Paul}}&nbsp; ,</p>n<p>I'm just testing please wait</p>n<p>yours faithfully,</p>n<p>&nbsp;";
document.write(myString.replace(/(.*?{{)(.*?)|(.*?)(?=}})/g, "$1/$2 to $3/"));

我认为这就是你要找的...

var p = document.getElementById('greetings');
p.innerText = p.innerText.replace(/.*?{{([ws]+)|([ws]+)}}/, "/$1 to $2/");
<p id="greetings">Dear sir&nbsp;&nbsp; {{heelo|Paul}}&nbsp; ,</p>n<p>I'm just testing please wait</p>n<p>yours faithfully,</p>n<p>&nbsp; 

最新更新