Search code examples
regexstringregex-lookaroundsregex-groupregexp-replace

Regex between elements for specific characters


Say I have the following String:

&<div>test & test & test</div><&>

How would I go about finding all the & in between the element tags, i.e. ></? (doesn't have to be specific to divs)

So far I've gotten >.*(&).*<, but that only finds the last & in between the ></.

For context, I eventually need to use this regex to translate certain special characters to use the appropriate escape character, but only in between the elements.


Solution

  • To match only the &, use a look ahead:

    &(?=[^<>]*</)
    

    It’s not bullet proof, but will hopefully work for your input.