Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
什么是javascript中的正则表达式_Javascript_Regex - Fatal编程技术网

什么是javascript中的正则表达式

什么是javascript中的正则表达式,javascript,regex,Javascript,Regex,我有下面的字符串 这是对正则表达式的测试,这是对正则表达式的测试 我只想换一个 嗨,这是正则表达式的测试 用其他字符串分段 字符串“sssHi这是正则表达式的测试”中的第一段不应替换 我为同样的目的编写了以下正则表达式: /([^.]Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)|(Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)$/ 但这两个部分都匹配。我只想匹配第二个,因为第一个片段的

我有下面的字符串

这是对正则表达式的测试,这是对正则表达式的测试

我只想换一个

嗨,这是正则表达式的测试

用其他字符串分段

字符串“sssHi这是正则表达式的测试”中的第一段不应替换

我为同样的目的编写了以下正则表达式:

/([^.]Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)|(Hi\sthis\sis\sthe\stest\sfor\sregular\sExpression)$/
但这两个部分都匹配。我只想匹配第二个,因为第一个片段的前缀是“sss”

应该什么都不匹配,除了换行,对吗?So组

  "([^.]anystring)"
应该只匹配“anystring”,该字符串前面没有除换行符以外的任何字符。 我说得对吗

任何想法。

匹配前面没有其他字符串的字符串是一个字符串,JavaScript的正则表达式引擎不支持该字符串。但是,您可以使用回调来执行此操作

给定

使用回调检查
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=“这是对正则表达式的测试”
    • $1=“s”
    • $0=“,您好,这是对正则表达式的测试”
    • $1=“,”
  • 如果
    $1==“s”
    匹配项被替换为
    $0
    ,因此它保持不变,否则它被替换为
    $1+“替换”

    另一种方法是匹配第二个字符串,即要替换的字符串,包括分隔符

    要匹配前面带有逗号的
    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"
    
    使用


    *是贪婪的,因此匹配尽可能长的字符串,剩下的字符串留给您想要匹配的显式字符串。

    。括号内的运算符与括号外的运算符含义不同。括号内是一个文字句点(.)使用
    \b
    。e、 g.
    \b(您好,这是测试
    )\b
    读取
    前瞻
    前瞻
    断言@diEcho:Javascript不支持前瞻,但
    前瞻
    可能有用
    str.replace(/(\W)Hi this is the test for regular Expression/g, "$1replacement")
    // => "sssHi this is the test for regular Expression,sr,replacement"
    
    str.replace(/Hi this is the test for regular Expression$/g, "replacement")
    // => "sssHi this is the test for regular Expression,sr,replacement"
    
    str.replace(/(.*)Hi this is the test for regular Expression/,"$1yourstring")