skip to Main Content

I have regex which uses a look ahead assertion to match strings of the format {{ x }}. The regex is /(?<={{s)[^}s]+(?=s*}})/gm

How can I achieve this without using a look ahead assertion?

2

Answers


  1. Try with this:

    {{s([^}s]+)s*}}

    Your result will be inside the first group (the rules inside ())

    Login or Signup to reply.
  2. Adding to the other answers, if you want a list of all "x values", you can produce one by repeatedly evaluating m[1], which is the first group, where m is one of the matches.

    The following variants with and without lookaround are equivalent:

    /* With lookaround */
    const s = "{{ 1 }}{{ 2 }}";
    console.log(s.match(/(?<={{s*)[^}s]+(?=s*}})/gm));
    /* Without lookaround */
    for (var matches = [], m, regex = /{{s*([^}s]+)s*}}/gm; m = regex.exec(s);)
      matches.push(m[1]);
    console.log(matches);

    The question remains, however: Why do you want to avoid lookarounds?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search