Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading