0

I need java regex to extract only domain name from a string.

Ex:

input : www.google.com  (ouput) --> google.com
    input : https://www.google.com (output) --> google.com

Basically it should remove all www and http(s) from URL. Please help!

Thanks!

5
  • 3
    Don't use regex for this. Commented Sep 17, 2014 at 7:23
  • What have you tried? Where are you stuck? Post your attempted regex(es) in your question. Commented Sep 17, 2014 at 7:25
  • There is URL class in Java for this. Commented Sep 17, 2014 at 7:26
  • 3
    Check this stackoverflow.com/questions/9607903/… Commented Sep 17, 2014 at 7:30
  • stackoverflow.com/questions/569137/… Commented Sep 17, 2014 at 7:32

3 Answers 3

1

If you interested it doing in regex, try something like this :

urlString.replaceFirst("^(https?://)?(www\\.)?", "") 

However that won't be good idea as comments are suggesting.

Sign up to request clarification or add additional context in comments.

Comments

0
.*?\.(.*?\.[a-zA-Z]+)

Try this.See demo.

http://regex101.com/r/jT3pG3/33

1 Comment

it finds and matches a string like this: "weionheotiwot.w0ioghw0ogiwjgt.wghwoigh"
-1

to achieve this, you need 2 java classes: Matcher and Pattern.

you have to build up the Pattern object and call on it the method which gives you the matcher instance.

// in the beginning, import necessary classes
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches
{
    public static void main( String args[] ){

      // this is the array with urls to check
      String [] urls = {"https://google.com", "www.google.com"};

      // now, let's check if strings are matching
      for (int i = 0; i < urls.length; i++) {  

          // string to be scanned to find the pattern
          String url = urls[i];
          String pattern = "google.com";

          // create a Pattern object
          Pattern p = Pattern.compile(pattern);

          // now, create Matcher object.
          Matcher m = p.matcher(url);

          // let's check if something was found
          if (m.find()) {

             System.out.println("Found value: " + url);

          } else {

             System.out.println("NO MATCH");

          }

       }

   }

}

you can add to the array all the urls you want the pattern to check!

1 Comment

I think the OP wants a more general solution that also works for other domains than google.com

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.