匹配而不是的字符串是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