JavaScript中的正则表达式是什么?

3

我有以下字符串

sssHi this is the test for regular Expression,sr,Hi this is the test for regular Expression

我想仅替换

Hi this is the test for regular Expression

这一部分为其他字符串。

字符串 "sss Hi this is the test for regular Expression" 中的第一个部分不应被替换。

我写了以下正则表达式:

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

但它匹配了两个片段。我希望只匹配第二个,因为第一个片段以“sss”为前缀。
[^.]      

应该只匹配换行符,对吧?所以这个组

  "([^.]anystring)"

我应该只匹配“任何字符串”,它不是由任何字符(除了换行符)引导的。我的理解正确吗?

你有什么想法?


3
方括号内的"."运算符与外部含义不同。在方括号内,它是一个字面上的句点(.)。 - frostmatthew
5
使用\b。例如,\b(这是测试)...\b`。 - Brad Christie
请在此处阅读有关“前瞻”和“后顾”的断言的内容:http://www.regular-expressions.info/lookaround.html#lookahead - xkeshav
2
@diEcho:Javascript 不支持后顾断言。 - Bergi
@Bergi 这仍然是误导性的,请不要使用它。抱歉,在Matrix中还没有这样的实现,我认为也没有。但是,我尚未排除将lookbehind的实现添加到[JSX:regexp.js](http://pointedears.de/websvn/filedetails.php?repname=JSX&path=%2Ftrunk%2Fregexp.js)中,该文件已经支持了几个PCRE功能。 - PointedEars
显示剩余4条评论
2个回答

3

匹配一个未被另一个字符串先行的字符串,这是一种负向预测先行断言,在 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"`,则匹配保持不变,否则替换为 `$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"

0

使用

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

.* 是贪婪的,因此匹配最长可能的字符串,留下其余部分供您想要匹配的显式字符串使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接