我有一个如下所示的字符串:
"This is a test [Text that (cannot) be changed]. But (this) can be changed."
我想用html替换(
和)
内的字符串,但是当它们在[ ]
内时却不能。我想用不同的html替换[ ]
中的所有文本。我的最终结果如下所示。
"This is a test <p>Text that (cannot) be changed</p>". But <b>this</b> can be changed."
我创建了一个表达式,可以选择[ ]
字符串之外的所有内容。但是,我该如何仅对此选定文本执行替换?要选择[ ]
以外的所有内容,请使用以下内容:
([^\[\]]+)(?:\s|$|\[)
这会选择[
和]
之外的所有文字。我想仅对此选定文本执行( )
的正则表达式替换。
答案 0 :(得分:2)
您可以组合使用正则表达式和回调函数来替换所需的内容:
var subject = 'This (is) a test [Then some text that (cannot) (be) changed]. But (this) (can) be changed.';
var regex = /(?:^|])([^\[]*)(?:\n|$|\[)/g;
var replace = subject.replace(regex, function(match, p1)
{
return match.replace(/\(/g, '<b>').replace(/\)/g, '</b>');
});
console.log(replace);
// This <b>is</b> a test [Then some text that (cannot) (be) changed]. But <b>this</b> <b>can</b> be changed.
演示:http://jsfiddle.net/q21sns3s/2/
正则表达式解释:
(?:^|])
:我们需要主题的开头或结束]
([^\[]*)
:后面跟着一个开头[
(?:\n|$|\[)
:以开头[
,新行或主题结尾($
)结束
答案 1 :(得分:2)
此处的最佳方法在使用don't catch this|(do catch this)
技术的 this SO answer 中进行了解释。我的正则表达是这样的:
\[[^\]]*]|\(([^)]*)\)
所以我抓住[]
之间的所有内容以及()
之间的所有内容,但只有后者会生成一个包含您想保留的文本的捕获组。然后我可以检查这个捕获组来决定做什么:不改变它或者在它周围放置<b></b>
。
var subject = 'This (is) a test [Then some text that (cannot) (be) changed]. But (this) can (be) changed.';
var regex = /\[[^\]]*]|\(([^)]*)\)/g;
var replace = subject.replace(regex, function(match, p1)
{
return (p1==undefined)?match:'<b>'+p1+'</b>';
});
console.log(replace);
// This <b>is</b> a test [Then some text that (cannot) (be) changed]. But <b>this</b> can <b>be</b> changed.
&#13;
(感谢@johansatge提供了很好的模板,我只是更改了正则表达式和return
行)
答案 2 :(得分:0)
在您提取的文字上使用/[(][a-z]+[)]/g
,您可以替换文字"(this)"
var newText = myExtractedText.replace(/[(][a-z]+[)]/g, "(new text)");
编辑:
要最初替换字符串中的文本(首先在'[]'中提取内容,你可以这样做:
var s = "This is a test [Text that (cannot) be changed]. But (this) can be changed.",
match = s.match(/[a-z ]+([(][a-z]+[)])[a-z .]+$/ig)[0];
console.log(match.replace(/[(][a-z]+[)]/, '(new text)'));
答案 3 :(得分:0)
(?!\[)\(.*?\)(?<!\])
您可以像here中所述模仿此功能。不过它认为@funkwurm的答案似乎更清晰。这是解决这类问题的最好方法。