在正则表达式中,如果第一个圆括号没有't匹配,当在JavaScript中使用replace()与在Ruby中使用

In Regular Expression, if the first parenthesis doesn't match, can $1 be empty string when using replace() in JavaScript vs gsub in Ruby?

本文关键字:当在 replace JavaScript Ruby 与在 匹配 圆括号 第一个 如果 正则表达式      更新时间:2023-09-26

使用JavaScript,要从foo.bar中提取前缀foo.(包括.),我可以使用:

> "foo.bar".replace(/('w+.)(.*)/, "$1")
"foo."

但如果没有这样的前缀,我希望它给出一个空字符串或null,但它给出了完整的字符串:

> "foobar".replace(/('w+.)(.*)/, "$1")
"foobar"

为什么$1会给出整个字符串?——正如我认为的第一个括号。

  1. 也许它的意思是真正匹配的第一个括号
  2. 如果#1是真的,那么可能一种常见的标准技术是使用?,它在Ruby中工作:

    使用irb:

    > "foo.bar".gsub(/('w+'.)?(.*)/, ''1')
    "foo."
    > "foobar".gsub(/('w+'.)?(.*)/, ''1')
    ""
    

    因为?是可选的,而且它无论如何都会匹配。然而,它在JavaScript:中不起作用

    > "foobar".replace(/('w+.)?(.*)/, "$1")
    "foobar"
    

    我可以在JavaScript中使用match()来做这件事,它会很干净,但只是为了更多地理解replace()

  3. 是什么原因导致它在Ruby和JavaScript中的工作方式不同,上面的#1和#2也适用吗?和/或如果使用replace()不存在前缀,有什么好的替代方法可以"抓取"前缀或获取""

FYI,我认为JavaScript的正则表达式不正确,因为它没有转义.(点)字符。

$1返回整个字符串的原因是$1诱使您相信它与第一组匹配(这不是真的)。

/* your js regex is /('w+.)/, I use /('w+'.)/ instead to demonstrate it */
"foobar".replace(/('w+'.)/, "$1"); // 'foobar'

这是因为$1(empty)不匹配,所以正则表达式试图用$1替换原始字符串foobar(因为它与任何内容都不匹配,它只返回整个原始字符串

"foobar".replace(/('w+'.)/, '-');    // 'foobar' (No matches, so nothing get replaced)
"foobar".replace(/('w+'.)/, '$1');   // 'foobar' (No matches, $1 is empty, nothing get replaced)
"foobar.a".replace(/('w+'.)/, '-');  // '-a' (matches 'foobar.' so replaces 'foobar.' with '-') + ('a')
"foobar.a".replace(/('w+'.)/, '$1'); // 'foobar.a' (matches 'foobar.' so replaces 'foobar.' with itself) + ('a')

无论您是否成功更改了原始字符串,JavaScript中的replace方法都会为您提供原始字符串的副本。

例如:

alert( "atari.teenageRiot".replace(/5/,'reverse polarity of the neutron flow') );
//"atari.teenageRiot"

替换与查找匹配项无关。这是关于通过用第二个参数替换与第一个参数匹配的字符串来更改字符串,这样无论是否更改,都可以返回要更改的字符串。

另外,我会用这个来代替:

"foo.bar".replace(/('w+'.)(.*)/, "$1")

您在.之前没有',因此它被视为与大多数字符匹配的通配符。

相关文章: