我有这样的完整链接:
http://localhost:8080/suffix/rest/of/link
如何在 Java 中编写正则表达式,它只返回带有后缀的 url 的主要部分:http://localhost/suffix
而没有:/rest/of/link
?
- 可能的协议(protocol):http, https
- 可能的端口:多种可能性
我假设我需要在第 3 次出现 '/'
标记(包括)后删除整个文本。
我想按下面的方式做,但我不太了解正则表达式,请问你能帮忙如何正确编写正则表达式吗?
String appUrl = fullRequestUrl.replaceAll("(.*\\/{2})", ""); //this removes 'http://' but this is not my case
最佳答案
我不确定您为什么要为此使用正则表达式。 Java 提供了一个 Query URL Objects 为您做同样的事情。
这是从同一个 site 中获取的示例展示它是如何工作的:
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
关于java - 如何通过正则表达式删除 URL 的某些部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19254720/