19

I would like to match ampersand (&) but not when it exists in following manner

'
"
>
<
&
&#

So in the following line & MY& NAME IS M&Hh. ' " > < & &# &&&&&&

I want it to match all ampersands except those which exist in ' " > < & &#

1 Answer 1

34

That looks like a job for negative lookahead assertions:

&(?!(?:apos|quot|[gl]t|amp);|#)

should work.

Explanation:

&        # Match &
(?!      # only if it's not followed by
 (?:     # either
  apos   # apos
 |quot   # or quot
 |[gl]t  # or gt/lt
 |amp    # or amp
 );      # and a semicolon
|        # or
 \#      # a hash
)        # End of lookahead assertion
2
  • 5
    Nice regex, Tim. I'm still in love with this tool, so pardon me while I link a fancier diagram.
    – Patrick M
    Commented Feb 13, 2014 at 4:38
  • I wish I had more than one vote. This was a very helpful answer! Exactly what I was looking for.
    – Chris
    Commented Oct 17, 2019 at 2:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.