开发者

Help with Regexp

开发者 https://www.devze.com 2023-03-01 02:56 出处:网络
Given the test string: <div class=\"comment-quoter\">Comment by <strong>Tom</strong>

Given the test string:

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

I want to change it to

开发者_StackOverflow社区[quote=Tom]

I've got as far as this but it gets no matches:

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


Try:

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

The round brackets denote the $1 capture group, so the curly brackets and comma would match literals and aren't necessary.

Dependent on what you're expecting, you can make it less greedy by being more specific about the characters you're matching for the capture group:

(\w+)

would match one or more alpha-numeric characters and would return correct matches if you have more than one quote in your input string.


If you want to do it without the overhead of explicitly creating a new RegExp object (since you're not storing it anyway) just do this:

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]')
0

精彩评论

暂无评论...
验证码 换一张
取 消