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)
What I don’t understand is where does the second match/group (output2) come from. Amy suggestions?
2
Answers
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.
As Pointy mentioned, you have two capturing groups.
If you use a named capturing group, this makes the code easier to write and understand: