匹配而不是的字符串是negative lookbehind,不支持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(/Hi this is the test for regular Expression$/g, "replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
:
str.replace(/(\W)Hi this is the test for regular Expression/g, "$1replacement")
// => "sssHi this is the test for regular Expression,sr,replacement"
要在一行的末尾匹配str
。括號內的操作符與外部操作符不同。在括號內,它是一個字面句點(。) – Exupery 2012-07-16 12:51:40
使用'\ b'。例如'\ B(你好,這是test' ...')\ B' – 2012-07-16 12:51:49
閱讀'lookahead'和'lookbehind'斷言[這裏](http://www.regular-expressions.info/lookaround.html#lookahead) – diEcho 2012-07-16 12:58:57