Using Matcher to extract URL domain name

我的未来我决定 提交于 2019-12-23 03:31:48

问题


    static String AdrPattern="http://www.([^&]+)\\.com\\.*";
    static Pattern WebUrlPattern = Pattern.compile (AdrPattern);
    static Matcher WebUrlMatcher;
                WebUrlMatcher = WebUrlPattern.matcher ("keyword");
                if(WebUrlMatcher.matches())
             String  extractedPath = WebUrlMatcher.group (1);

Considering above codes, My aim is to extract the domain name from the URL and dismiss the rest. But the trouble is that, first of all, if the URL has deeper path, it will not ignore it and second, it does not work for all URL with .com extension.

For example, if the URL is http://www.lego.com/en-us/technic/?domainredir=technic.lego, the result will not be lego but lego.com/en-us/technic/?domainredir=technic.lego.


回答1:


Use

static String AdrPattern="http://www\\.([^&]+)\\.com.*";
                                    ^^              ^

You escaped the final dot, and it was treated as a literal, and matches could not match the entire string. Also, the first dot must be escaped.

Also, to make the regex a bit more strict, you can replace the [^&]+ with [^/&].

UPDATE:

static String AdrPattern="http://www\\.([^/&]+)\\.com/([^/]+)/([^/]+)/([^/]+).*";
static Pattern WebUrlPattern = Pattern.compile (AdrPattern);
static Matcher WebUrlMatcher = WebUrlPattern.matcher("http://www.lego.com/en-us/technic/?domainredir=technic.lego");
if(WebUrlMatcher.matches()) {
    String  extractedPath = WebUrlMatcher.group(1);
    String  extractedPart1 = WebUrlMatcher.group(2);
    String  extractedPart2 = WebUrlMatcher.group(3);
    String  extractedPart3 = WebUrlMatcher.group(4);
}

Or, with \G:

static String AdrPattern="(?:http://www\\.([^/&]+)\\.com/|(?!^)\\G)/?([^/]+)";
static String AdrPattern="http://www\\.([^/&]+)\\.com/([^/]+)/([^/]+)/([^/]+)";
static Pattern WebUrlPattern = Pattern.compile (AdrPattern);
static Matcher WebUrlMatcher = WebUrlPattern.matcher("http://www.lego.com/en-us/technic/?domainredir=technic.lego");
int cnt = 0;
while(WebUrlMatcher.find()) {
    if (cnt == 0) {
       String extractedPath = WebUrlMatcher.group(1);
       String extractedPart = WebUrlMatcher.group(2);
       cnt = cnt + 1;
    }
    else {
       String extractedPart = WebUrlMatcher.group(2);
    }
}


来源:https://stackoverflow.com/questions/32051819/using-matcher-to-extract-url-domain-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!