匹配一个未被另一个字符串先行的字符串,这是一种负向预测先行断言,在 JavaScript 的正则表达式引擎中不支持。但是您可以使用回调函数来实现。
假设
str = "sssHi this is the test for regular Expression,sr,Hi this is the test for regular Expression"
使用回调函数来检查 str
前面的字符:
str.replace(/(.)Hi this is the test for regular Expression$/g, function($0,$1){ return $1 == "s" ? $0 : $1 + "replacement"; })
正则表达式匹配了两个字符串,因此回调函数被调用了两次:
1. 匹配到
```
$0 = "sHi this is the test for regular Expression"
$1 = "s"
```
2. 匹配到
```
$0 = ",Hi this is the test for regular Expression"
$1 = ","
```
如果 `$1 == "s"`,则匹配保持不变,否则替换为 `$1 + "replacement"`。
另一种方法是匹配第二个字符串,即要替换的字符串(包括分隔符)。
例如,要匹配以逗号为前缀的 `str`:
str.replace(/,Hi this is the test for regular Expression/g, ",replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
为了匹配在任何非单词字符之前的
str
:
str.replace(/(\W)Hi this is the test for regular Expression/g, "$1replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
要在行末匹配str
:
str.replace(/Hi this is the test for regular Expression$/g, "replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
\b
。例如,\b(这是测试)...
\b`。 - Brad Christie