在String.split()中使用捕获组 [英] Use of capture groups in String.split()

查看:169
本文介绍了在String.split()中使用捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ node
> "ababaabab".split(/a{2}/)
[ 'abab', 'bab' ]
> "ababaabab".split(/(a){2}/)
[ 'abab', 'a', 'bab' ]
>

所以,这对我来说没有意义。有人可以解释一下吗?我不明白'a'出现的原因。

So, this doesn't make sense to me. Can someone explain it? I don't get why the 'a' shows up.

注意:我正在尝试匹配双倍的行结尾(可能在Windows文件中)所以我分裂 /(\ r?\\ \
){2} /
。但是我在我的数组中得到了无关的'\015 \ n'条目(注意 \015 == \ r )。

Note: I am trying to match for doubled line endings (possibly on windows files) so I am splitting on /(\r?\n){2}/. However I get extraneous '\015\n' entries in my array (note \015 == \r).

为什么会出现这些?

注意:也会影响浏览器中的JS引擎,所以这个特定于JS而不是节点。

Note: also affects JS engine in browsers so this is specific to JS not node.

推荐答案

在第二个结果中, a 正在出现,因为你已将它包装在一个捕获组中()(括号)。

In your second result, a is appearing because you've wrapped it in a capture group () (parentheses).

如果你想要要包含它,但仍需要条件组,请使用非捕获组:(?:a)。 questionmark-colon可以在任何捕获组中使用,它将从结果列表中省略。

If you want to not include it but you still require a conditional group, use a non-capturing group: (?:a). The questionmark-colon can be used inside any capture group and it will be omitted from the resulting list of captures.

这是一个简单的例子: http://regex101.com/r/yM1vM4

Here's a simple example of this in action: http://regex101.com/r/yM1vM4

这篇关于在String.split()中使用捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆