java - 如何通过正则表达式删除 URL 的某些部分?

标签 java regex string

我有这样的完整链接:

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/

相关文章:

java - Selenium IE 驱动程序无法在 VPN 上运行

android - 如何识别编辑文本中的初始空格?

regex - Apache RewriteRule - 无法匹配字符串的开头

python - 如何在 Python 中使用 JSON 从文件的特定列表中检索特定字符串

c - "Wide character array initialized from non-wide string"是什么意思,我如何在 C 中更正它?

java - Spring Boot 存储库在测试期间不工作

java - LibGDX 如何使用 Sprites 和 SpriteBatch 在单个位置组合 2 个纹理以进行多重纹理

java - 在 Apache Poi 中打印 Unicode 字符

javascript - 持续时间的正则表达式

javascript - 如何在数组上使用 .filter() 仅删除 'NaN' 而不是字符串和数字?