Search code examples
regexstringconditional-statementsmime

Finding match by negating (based on a missing string)


I've been googling a lot about this. What I'm trying to achieve is the next: I have to check in a regex condition if a MIME is NOT of a specific type.

For example, I have recevied the next message:

image/png, image/jpeg, document/pdf

I would like to detect the document/pdf part only , which is a MIME type, a string, that does NOT start with image/

But no matter how hard I looked, tried and played around with the RegExBody software, I just utterly fail to match it..

I'm posting this in despair and hopes that maybe an expert regex could help me out..

I tried many approaches, mainly: Finding out the non-image type, regardless if there is one or not.

It just refuses to work. I tried positive lookahead and negative lookahead. But I probably used it wrong somehow. I can't post the examples because I have tried and deleted so many. The one that seemed really close to working was \b(?:(?!image/\w+))\w+\b but it just persists on selecting the second part of the non-matching pattern. If I use: image/png It gets the: png Which means it would still return true although I meant it to ignore image/ types..


Solution

  • You should have added a /\w+ part after \w+ to match your substring:

    \b(?!image/)\w+/\w+\b
    

    See the regex demo

    Pattern details:

    • \b - word boundary
    • (?!image/) - a negative lookahead failing the match if there is image/ right after the current location
    • \w+/\w+ - 1+ word characters followed with / and again 1+ word characters
    • \b - a trailing word boundary