举个例子: 下面一段话,我想把“single word”和“word”都加上链接,If you need only translate a single word, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations.先替换“single word”:If you need only translate a <a href="">single word</a>, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations.再替换“word”: If you need only translate a <a href="">single <a href="">word</a></a>, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations.这样显然不是我想要的,而且这也不合规范,应该是:If you need only translate a <a href="">single word</a>, you will see a simple dictionary at the bottom indicating parts of speech and possible <a href="">word</a> variations.就是想匹配 字符或者字符串,而该字符或字符串不能 已经 加上链接 的 注:内容为英文,字符之间要么是空格,要么是标点符号
js除了正则直接量那种声明方式外,还有正则对象RegExp/(?:single\b[\W\s]+)?word/g 等同于new RegExp('(?:single\\b[\\W\\s]+)?word', 'g'); <script> var s = 'If you need only translate a single word, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations. ' alert( s.replace(/((?:single\b[\W\s]+)?word)/g, '<a>$1</a>') );alert( s.replace(new RegExp('(?:single\\b[\\W\\s]+)?word', 'g'), function (l) { return '<a>' + l + '</a>'; }) ); </script>
下面一段话,我想把“single word”和“word”都加上链接,If you need only translate a single word, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations.先替换“single word”:If you need only translate a <a href="">single word</a>, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations.再替换“word”:
If you need only translate a <a href="">single <a href="">word</a></a>, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations.这样显然不是我想要的,而且这也不合规范,应该是:If you need only translate a <a href="">single word</a>, you will see a simple dictionary at the bottom indicating parts of speech and possible <a href="">word</a> variations.就是想匹配 字符或者字符串,而该字符或字符串不能 已经 加上链接 的
注:内容为英文,字符之间要么是空格,要么是标点符号
/(single\b[\W\s]+)?word/g
标题的问题求 某字符前后 非 字母、数字、标点符号、a> 的正则表达式(?<!M字符集)A字符(?!M字符集)不支持反向预查(?<!pattern)的话,我们可以变通下
用replace加委托配合式子分支选择...方法伪代码
v.replace(/(?:M字符集A字符|(A字符))(?!M字符集)/g, function (l, $1) {
return $1 ? handler($1) : l;
});
<script>
var s = 'If you need only translate a single word, you will see a simple dictionary at the bottom indicating parts of speech and possible word variations. '
alert(
s.replace(/((?:single\b[\W\s]+)?word)/g, '<a>$1</a>')
);alert(
s.replace(new RegExp('(?:single\\b[\\W\\s]+)?word', 'g'), function (l) {
return '<a>' + l + '</a>';
})
);
</script>
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};可以用这个方法转义下...
如new RegExp(RegExp.escape('()')).test('()'); //true