2012-07-16 32 views
3

我有以下字符串什么是JavaScript的

sssHi这是正则表达式测试正则表达式,SR,你好,这是正则表达式测试

我想只能更换

你好,这是正则表达式测试

段与其他一些字符串。

在字符串中的第一段“SSS 你好,这是测试对正则表达式”不应该被更换

我写了下面的相同的正则表达式:

/([^.]Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)|(Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)$/ 

但两个细分匹配。我想只匹配第二个,因为第一个字母的前缀是“sss”。

[^.]  

应该除了换行符之外什么都不能匹配?所以群组

"([^.]anystring)" 

应该只匹配除了换行符之外没有任何chanrachter的“anystring”。 我正确吗?

任何想法。

+3

。括号内的操作符与外部操作符不同。在括号内,它是一个字面句点(。) – Exupery 2012-07-16 12:51:40

+5

使用'\ b'。例如'\ B(你好,这是test' ...')\ B' – 2012-07-16 12:51:49

+0

阅读'lookahead'和'lookbehind'断言[这里](http://www.regular-expressions.info/lookaround.html#lookahead) – diEcho 2012-07-16 12:58:57

回答

3

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

正则表达式两个字符串匹配,从而在回调函数被调用两次:

  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"比赛被$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

0

使用

str.replace(/(.*)Hi this is the test for regular Expression/,"$1yourstring") 

。*是贪婪的,因此匹配可能最长的字符串,留下其余为你想匹配明确字符串。