skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. As Pointy mentioned, you have two capturing groups.

    If you use a named capturing group, this makes the code easier to write and understand:

    const test = `this is the start
    a
    b
    c
    e
    f
    end
    g
    h
    `;
    
    console.log(test.match(/start(?<between>(.|n)*)end/m).groups.between)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search