Search code examples
regexstringregex-negation

Is there any way of using the not (^) in regex for multiple characters?


I want to make a Regex pattern that matches all relative paths.

What I want to match:

<img src="image.png"
<img src="http_image.png"

What I don't want to match:

<img src="http://example/image.png"

I tried matching with these patterns, but none of them work:

\src="[^http://]\
\src="^(http://)\
\src="[^h][^t][^t][^p][^:][^/][^/]\
\src="([^h][^t][^t][^p][^:][^/][^/])\

The src attribute will always be formatted with double-quotes ("), not single-quotes ('). It will always contain an "http" source, not "https" or others.


Solution

  • The way to solve this is by using negative lookahead assertion:

    ^img src="(?!http:\/\/\S+).*"$
    

    Rubular link

    ^                  : Start anchor
    img src="          : Literal img src="
    (?!http:\/\/\S+)   : To ensure the string following " is not a URL
    .*                 : Anything else is allowed
    "                  : Literal "
    $                  : End anchor