0

Let's say I have this url:

https://www.google.com/search?q=test&tbm=isch&randomParameters=123

I want to match google's search url, when it doesn't contain:

tbm=isch

tbm=news

param1=432

I've tried this pattern:

^http(s):\/\/www.google.(.*)\/(search|webhp)\?(?![\s]+(tbm=isch|tbm=news|param1=432))

but it's not working (as in still matching), the sample url

6
  • @CinCout It's still matching, even though it shouldn't
    – Cornwell
    Jul 1, 2016 at 11:52
  • 2
    [\s]+ - why? Did you mean .*? or [\S]*? Jul 1, 2016 at 11:55
  • 1
    In what language/library are you trying to use this regexp? Jul 1, 2016 at 11:56
  • 1
    @MariaDeleva I deleted my comment by mistake. That was it. Not sure how I overlooked it. If you create an answer, I'll accept it
    – Cornwell
    Jul 1, 2016 at 12:00
  • What language do you use? Jul 1, 2016 at 12:17

3 Answers 3

3

You could use:

^                         # anchor it to the beginning
https?://                 # http or https
(?:
    (?!tbm=(?:isch|news)) # first neg. lookahead
    (?!param1=432)        # second
    \S                    # anything but whitespace
)+
$                         # THE END

See a demo on regex101.com.
There might be builtin-methods like urlparse() for your specific programming language though.

2

Your regex should be

^https:\/\/www.google.([^\/]*)\/(search|webhp)\?(?!.*(tbm\=isch|tbm\=news|param1\=432)).*$

example

The issue was that you were trying to do lookahead with \s* instead of .* which will match any number of characters.

Also www.google.(.*) would have caused a lot of backtracking causing performance issue so I have replaced it with www.google.([^\/]*)


Edit

Am wondering why you are using regex for this instead of simple indexof or similar methods from the language you are using. Any special usecase here??

1

You should change the [\s]+ to .*? or [\S]*? and your regex will work. To also match the whole url, if it fits the criteria, you can add another [\S]* at the end:

^http(s):\/\/www.google.([\w\.]*)\/(search|webhp)\?(?![\S]*?(tbm=isch|tbm=news|param1=432))[\S]*
0

Your Answer

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

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