正则表达式:使用量词捕获多个组 [英] Regular Expressions: Capture multiple groups using quantifier

查看:137
本文介绍了正则表达式:使用量词捕获多个组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">

var str = '<12> rnbqkb-r Rnbq-b-r ';

var pat1 = new RegExp('^\\<12\\> ([rnbqkpRNBQKP-]{8}) ([rnbqkpRNBQKP-]{8})');
var pat2 = new RegExp('^\\<12\\> ([rnbqkp RNBQKP-]{8}){2}');
var pat3 = new RegExp('^\\<12\\> ([rnbqkp RNBQKP-]{8}){2}?');

document.write(str.match(pat1));
document.write('<br />');
document.write(str.match(pat2));
document.write('<br />');
document.write(str.match(pat3));

</script>
</body>
</html>

产生

<12> rnbqkb-r Rnbq-b-r,rnbqkb-r,Rnbq-b-r
<12> rnbqkb-r Rnbq-b-, Rnbq-b-
<12> rnbqkb-r Rnbq-b-, Rnbq-b-

作为输出。

为什么既没有模式 pat2 也没有 pat3 捕获第一组 rnbqkb-R ?我想捕获所有组,而不必像在模式 pat1 中那样明确地重复它们。

Why does neither pattern pat2 nor pat3 capture the first group rnbqkb-r? I would like to capture all groups without having to repeat them explicitly as in pattern pat1.

推荐答案


为什么模式pat2和pat3都没有捕获第一组rnbqkb-r?

Why does neither pattern pat2 nor pat3 capture the first group rnbqkb-r?

因为你的正则表达式 pat2 pat3 的每个8字符序列末尾都有空格允许。

Because you have white-space at the end of each 8-character sequence that your regexes pat2 and pat3 do not allow.


我想捕获所有组,而不必像模式pat1那样明确地重复它们。

I would like to capture all groups without having to repeat them explicitly as in pattern pat1.

你不能。

当正则表达式只包含一个组时,不可能(在JavaScript中)捕获两个组。

It is not possible (in JavaScript) to capture two groups when your regex only contains one group.

通过括号定义组。您的匹配结果将包含与正则表达式中的括号对一样多的组(除了修改后的括号,例如(?:...),这将不计入匹配组)。想要在匹配结果中进行两次单独的小组赛吗?在正则表达式中定义两个单独的组。

Groups are defined thorugh parentheses. Your match result will contain as many groups as there are parentheses pairs in your regex (except modified parentheses like (?:...) which will not count towards match groups). Want two separate group matches in your match result? Define two separate groups in your regex.

如果一个组可以多次匹配,则该组的值将是 last 匹配的任何值。该组的所有上一场比赛将被其最后一场比赛覆盖。

If a group can match multiple times, the group's value will be whatever it matched last. All previous match occurrences for that group will be overridden by its last match.

尝试

var pat1 = /^<12> ((?:[rnbqkp-]{8} ?)*)/i,
    match = str.match(pat1);

if (match) {
  match[1].split(/\s+/);  // ["rnbqkb-r", "Rnbq-b-r", ""]
}

注意:


  • 如果你不想要最后一个,请事先修剪 str 空数组值。

  • 通常,更喜欢正则表达式文字表示法( / expression / )。仅对从动态值生成的表达式使用 new RegExp()

  • < > 并不特别,你不需要逃避它们。

  • Trim str beforehand if you don't want the last empty array value.
  • In general, prefer regex literal notation (/expression/). Use new RegExp() only for expressions you generate from dynamic values.
  • < and > are not special, you don't need to escape them.

这篇关于正则表达式:使用量词捕获多个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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