我有以下字符串
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)"
应该只匹配前面没有除换行符之外的任何字符的“任何字符串”。 我说得对吗?
任何想法。
最佳答案
匹配一个不是前面有另一个字符串的字符串是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 这是正则表达式的测试"
$1 = "s"
- 与
$0 = ",嗨,这是正则表达式的测试"
$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"
关于javascript - 什么是javascript中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11504597/