2

我有这样的完整链接:

http://localhost:8080/suffix/rest/of/link

如何在Java中编写正则表达式,它将仅返回带有后缀的url的主要部分:http://localhost/suffix而没有:/rest/of/link

  • 可能的协议:http、https
  • 可能的端口:许多可能性

我假设我需要在第 3 次出现'/'标记(包括)后删除整个文本。我想按如下方式进行操作,但我不太了解正则表达式,您能帮忙请教如何正确编写正则表达式吗?

String appUrl = fullRequestUrl.replaceAll("(.*\\/{2})", ""); //this removes 'http://' but this is not my case
4

2 回答 2

5

我不确定您为什么要为此使用正则表达式。Java 提供了一个Query URL Objects来为您做同样的事情。

这是取自同一站点的示例,以显示其工作原理:

import java.net.*;
import java.io.*;

public class ParseURL {
    public static void main(String[] args) throws Exception {

        URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                           + "/index.html?name=networking#DOWNLOADING");

        System.out.println("protocol = " + aURL.getProtocol());
        System.out.println("authority = " + aURL.getAuthority());
        System.out.println("host = " + aURL.getHost());
        System.out.println("port = " + aURL.getPort());
        System.out.println("path = " + aURL.getPath());
        System.out.println("query = " + aURL.getQuery());
        System.out.println("filename = " + aURL.getFile());
        System.out.println("ref = " + aURL.getRef());
    }
}

这是程序显示的输出:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
于 2013-10-08T18:42:33.523 回答
2

代码获取 URL 的主要部分:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexpExample {
    public static void main(String[] args) {
        String urlStr  = "http://localhost:8080/suffix/rest/of/link";
        Pattern pattern = Pattern.compile("^((.*:)//([a-z0-9\\-.]+)(|:[0-9]+)/([a-z]+))/(.*)$");

        Matcher matcher = pattern.matcher(urlStr);
        if(matcher.find())
        {
            //there is a main part of url with suffix:
            String mainPartOfUrlWithSuffix = matcher.group(1);
            System.out.println(mainPartOfUrlWithSuffix);
        }
    }
}
于 2013-10-08T18:38:46.830 回答