Search code examples
javascriptregexregex-group

Regex result contains extra match/group with just a return


I would like to match everything between start and end given the following string:

const test = `this is the start
a
b
c
e
f
end
g
h
`;

I have the following regex

const output = test.match(/start((.|\n)*)end/m);

No, output[0] contains the whole string that matched (with start and end) output[1] is the match (everything between start and end) output[2] is only a return (\n)

DEMO

enter image description here

What I don't understand is where does the second match/group (output2) come from. Amy suggestions?


Solution

  • This part of your regular expression: ((.|\n)*) creates two capturing groups. The outer group collects all the matched "anything" characters matched by the inner * group. The inner group will contain the last matched single character.

    Note that you'd probably be better off with a slightly different regular expression to avoid the odd effect of collecting too many characters in the groups before backtracking takes over.