匹配一个前面没有另一个字符串的字符串是一种否定的后向查找,并且 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"; })
// => "sssHi this is the test for regular Expression,sr,replacement"
正则表达式匹配两个字符串,因此回调函数被调用两次:
- 和
$0 = "sHi this is the test for regular Expression"
$1 = "s"
- 和
$0 = ",Hi this is the test for regular Expression"
$1 = ","
如果$1 == "s"
匹配替换为$0
,则保持不变,否则替换为$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"