javascript - 什么是javascript中的正则表达式

标签 javascript regex

我有以下字符串

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/

相关文章:

php - 将数字索引的 PHP 数组传递给 javascript

ruby - 为什么 ruby​​ 的 JSON 解析器会吃掉我的反斜杠?

java - 在 Java 中使用正则表达式(一些特定字符)

c# - 正则表达式捕获可变长度的重复模式

php - preg_replace 当不在双引号内时

javascript - Angular-pdf-viewer 在 grunt 构建后无法工作

Javascript 2D 数组包含始终为 false(使用 PUSH)

javascript - 如何使用 Javascript 或 jQuery 代码调用 mousemove

JavaScript/JSP - 为什么 "CheckboxStateChange"事件监听器不起作用?

regex - sed:未终止的 `s' 命令 - 无法弄清楚需要转义的内容