如果通过常规方法在RegExp中存在量词,如何获取所有订阅匹配?

时间:2018-11-15 20:03:25

标签: javascript regex

例如

/\w+(\s(\w+))*\./g.exec("I love you.")

返回

["I love you.", " you", "you"]

" love""love"也是子字符串匹配,但未在返回的数组中显示为整个元素。

是否有通用的方法或库可以自动提取带括号的所有子字符串匹配项?

例如,上面输入相同的结果可能是:

["I love you.", [" love", " you"], ["love", "you"]]

,如果RegExp为/(\w)+(\s((\w)+))*\./g 每个字母数字字符都是一个子字符串匹配项, 那么结果将是:

[
    "I love you.",  // The full string of characters matched
    ["I"],          // The first parenthesis has a quantifier, so the corresponding element in the result is an array.
    [" love", " you"],
    ["love", "you"],
    [
        ["l", "o", "v", "e"],
        ["y", "o", "u"]
    ]   // The 4th parenthesis is affected by 2 quantifiers, so the corresponding element in the result is a nested array with depth 2.
]

或者也许:

[
    "I love you.",  // The full string of characters matched
    [
        "I", 
        ["I"]
    ], // Just like if we parse the substring into the part of RegExp
    [
        [
            " love", 
            [
                "love", 
                ["l", "o", "v", "e"]
            ]
        ],
        [
            " you",
            [
                "you",
                ["y", "o", "u"]
            ]
        ]
    ]
]

我知道上面的例子可以通过一次次地用较小的RegExp解析匹配的数据来完成, 但就我而言,RegExp更为复杂,因此我想了解这种情况的通用方法。

0 个答案:

没有答案