0

For example,

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

returns

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

" love" and "love" are also substring matches, but not shown as a whole element in the returned array.

Is there a general method or library to auto-fetch all substring matches in the parenthesis with quantifiers?

For example, the result with the same input above may be:

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

and if the RegExp is /(\w)+(\s((\w)+))*\./g where each alphanumeric character is a substring match, then the result would be:

[
    "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.
]

or maybe:

[
    "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"]
            ]
        ]
    ]
]

I know the example above could be done by parsing the matched data with smaller RegExp again and again, but in my case the RegExp is more complicated so I would like to know a general method for such situations.

Kong Kao
  • 173
  • 2
  • 10

0 Answers0