Java 11 中的正则表达式遇到问题

问题描述 投票:0回答:1

尝试从以下位置删除服务器名称: //some.server.name/path/to/a/dir (以 /path/to/a/dir 结尾)

我尝试了 3 个不同的正则表达式(硬编码有效),但另外两个看起来应该可以工作,但不能。谁能告诉我为什么吗?

猫测试.java

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test
{
public static void main(String[] args) throws Exception
{

        String rootPath="//server.myco.com/some/path/to/a/doc/root";
        rootPath = rootPath.replace("//[\\w.]*","");
        System.out.println("rootPath - "+rootPath);
        rootPath = rootPath.replace("//[^/]*","");
        System.out.println("rootPath - "+rootPath);
        rootPath = rootPath.replace("//server.myco.com","");
        System.out.println("rootPath - "+rootPath);

}
}

输出:

rootPath - //server.myco.com/some/path/to/a/doc/root
rootPath - //server.myco.com/some/path/to/a/doc/root
rootPath - /some/path/to/a/doc/root

Java 11.0.6:

$ java --version
openjdk 11.0.6 2020-01-14
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.6+10)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.6+10, mixed mode)
java regex java-11 string-matching
1个回答
0
投票

请避免使用正则表达式来解析 URL。如今大多数语言都包含将 URL 解析为各个部分的库。

这是一个正确的例子:

import java.net.MalformedURLException;
import java.net.URL;

public class ExtractPath {
    public static void main(String[] args) {
        String rootPath = "//server.myco.com/some/path/to/a/doc/root";
        String path = extractPath(rootPath);
        System.out.println(path.equals("/some/path/to/a/doc/root")); // true
    }

    public static String extractPath(String location) {
        if (location.startsWith("//")) {
            location = "file:" + location;
        }
        try {
            URL url = new URL(location);
            return url.getPath();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.