regexnegative-lookbehind

Regex: Detect pattern in multiline HTMLElement


Basicaly I need to exclude [my-property] detection when in the content of a div but have when it's an attribute.

I have this regex : /(?<!\>)(\[\s*@?[-_a-zA-Z0-9.$]*%?\s*])(=)(["'])/

And theses tests :

Should return a match

<div [ ngStyle ]="{'max-width.px': i * 2 + 5}"></div>
<div [ngClass]="[
    'class-one',
    'class-two',
    'class-three'
]"></div>
<div [style.right.%]="val"></div>
<div [@animation.trigger]="val"></div>
<img [attr.aria-label]="val" />
<div [my-property]="val"></div>
<div [my_property]="val"></div>
<div [myProperty$]="val"></div>

Below should return no match

<div [%invalidProperty]="val"></div>
<div [invalidProperty)="val"></div>
<div>[my-property]="val"</div>
<div>
    [my-property]="val"
</div>

Every test is correct but the last one, which also needs to be excluded.

How could I improve my negative lookbehind to exclude the last test ?

Regex 101


Solution

  • If negative lookbehind of variable/infinite length is acceptable, you could use

    (?<!>\s*)(\[\s*@?[-_a-zA-Z0-9.$]*%?\s*])(=)(["'])
    

    Demo here.

    If not, you'll need to match also everything since previous < to check the was no > between.

    (<[^>]*)(\[\s*@?[-_a-zA-Z0-9.$]*%?\s*])(=)(["'])
    

    Demo here. I assume it should OK for this situation, as you already match a bunch of staff around.

    Also, this solution comes with added bonus of lack of negative lookarounds, that are non supported by relatively recent versions of Safari.