繁体   English   中英

在正则表达式中,如果第一个括号不匹配,在JavaScript和Ruby中使用gsub时,$ 1是否可以为空字符串?

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

使用JavaScript提取前缀foo. 包括. foo.bar ,我可以使用:

> "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()话,“抓取”前缀或获取""一种很好的替代方法是什么? replace()

仅供参考,我认为您JavaScript的正则表达式不正确,因为它无法逃脱. (点)字符。

$1返回整个字符串的原因是$1欺骗了您,使其相信与第一个组匹配(这是不正确的)。

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

这是因为$1匹配任何内容(empty)然后regex尝试用$1替换原始字符串foobar (因为它不匹配任何内容,因此它只会返回整个原始字符串。为清楚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")

您以前没有\\ . 因此它被视为与大多数字符匹配的通配符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM