帮助使用Regexp

Help with Regexp

本文关键字:Regexp 帮助      更新时间:2023-09-26

给定测试字符串:

<div class="comment-quoter">Comment by <strong>Tom</strong>

我想把它改成

[quote=Tom]

我已经得到了这个,但它没有匹配:

PostTxt = PostTxt.replace(new RegExp("<div class='"comment-quoter'">Comment by <strong>{(.+),}</strong>", "g"), '[quote=$1]')

尝试:

PostTxt = PostTxt.replace(new RegExp("<div class='"comment-quoter'">Comment by <strong>(.+)</strong>", "g"), '[quote=$1]')

圆括号表示$1捕获组,因此花括号和逗号将匹配字面量,而不是必需的。

根据你的期望,你可以通过更具体地描述你为捕获组匹配的字符来使它不那么贪婪:

('w+)

将匹配一个或多个字母数字字符,如果输入字符串中有多个引号,则返回正确匹配。

如果您想要这样做,而不需要显式地创建一个新的RegExp对象(因为您无论如何都不存储它),只需这样做:

PostTxt = PostTxt.replace(/<div class="comment-quoter">Comment by <strong>(.+)<'/strong>/g, '[quote=$1]');
PostTxt = PostTxt.replace(/<div class="comment-quoter">Comment by <strong>(.+?)<'/strong>/g, '[quote=$1]')