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 ' " > < & &#

Munish
  • 193
  • 1
  • 4

1 Answers1

33

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
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 5
    Nice regex, Tim. I'm still in love with this tool, so pardon me while I [link a fancier diagram](http://www.regexper.com/#%26(%3F!(%3F%3Aapos%7Cquot%7C%5Bgl%5Dt%7Camp)%3B%7C%23)). – Patrick M Feb 13 '14 at 04:38
  • I wish I had more than one vote. This was a very helpful answer! Exactly what I was looking for. – Chris Oct 17 '19 at 02:02