regexregex-lookaroundsregex-look-ahead

Regex for this double handlebar pattern not working in the following case


I have created regex pattern for this: {{}}-{{}}-{{}}

(?<![^*])(^|[^{])\{\{[^{}]*\}\}(?!\})([-]{1}\{\{[^{}]*\}\}(?!\})){2}(?![^*])

Double handle bars repeated exactly 3 times with dashes in between.

But the regex pattern is failing for the following case:

-{{}}-{{}}-{{}}

i.e., the pattern is matching even though a dash(-) is present before the first double handlebars. It ideally shouldn't.


Solution

  • This part (?<![^*]) means that these should not be a char other than * directly to the left of the current position (which is also used in the negative lookahead at the end of the pattern)

    Instead you can assert a whitspace boundary to the left and to the right.

    Note that this part [-]{1} can be written as just -

    (?<!\S)\{\{[^{}]*\}\}(?:-\{\{[^{}]*\}\}){2}(?!\S)
    

    See a regex101 demo.