Search code examples
javaregex

Java - Need some help on a Regex pattern for matching both http and https


I'm struggling with getting my regex pattern to match. Here are my requirements...

Match the following domain ex, (google.com) with both http and https.

I have an array list of various URL's....

http://stackoverflow.com/questions/ask
https://ask.com/search
http://google.com/images
https://google.com/images

This is my Pattern:

final Pattern p = Pattern.compile( "(http:(?!.*google.com).*)" );

However, it's currently returning true for all my url's.

Again, I only want it to return true if http://www.google.com or https://www.google.com matches my current url.


Solution

  • Use this:

    Pattern.compile("^https?://(?!.*\\.google\\.com/)[^/]*");
    

    RegEx Demo

    RegEx Details:

    • ^: Start
    • https?: Match http or https
    • ://: Match ://
    • (?!.*google\\.com/): Negative lookahead to fail to match if there is a google.com/ is matched anywhere
    • [^/]*: Match 0 or more of any non-/ characters