java 正则表达式添加尾部斜杠

java regex add trailing slash

我正在尝试重定向 URL 以添加尾部斜杠

/news -> /news/
/news?param1=value1 -> /news/?param1=value
/news#anchor?param1=value1 -> /news/#anchor?param1=value1

我需要通过仅标识路径并添加 / 的正则表达式来完成此操作。没有参数的时候没有问题。

^(/[a-z0–9/_\-]*[^/])$ -> /

但是当有参数时,我无法创建将路径与参数分开的正则表达式。

有什么想法吗?谢谢

您不应将字符串的末尾与 $ 匹配,并且末尾也不需要 [^/]

^(/[a-z0–9/_\-]*)

const regex = new RegExp("^(/[a-z0–9/_\-]*)");
console.log("/news".replace(regex, "/"));
console.log("/news?param1=value1".replace(regex, "/"));
console.log("/news#anchor?param1=value1".replace(regex, "/"));

您尝试的模式仅匹配 /news,因为锚点 $ 断言字符串结束。

如果您省略锚点,它也会匹配 ?#,因为您使用 [^/] 匹配除正斜杠之外的任何字符。


您可以重复 1 次或多次匹配正斜杠后跟字符 class 中列出的任何字符 1 次或多次,以防止匹配 ///

在替换中使用完整匹配并添加正斜杠。

^(?:/[a-z0-9_-]+)+

Regex demo | Java demo

String regex = "^(?:/[a-z0-9_-]+)+";
String string = "/news\n"
     + "/news?param1=value1\n"
     + "/news#anchor?param1=value1";

Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(string);
String result = matcher.replaceAll("[=11=]/");

System.out.println(result);

输出

/news/
/news/?param1=value1
/news/#anchor?param1=value1

注意在你的正则表达式中,0–9这部分的hyphen

https://www.compart.com/en/unicode/U+2013 instead of https://www.compart.com/en/unicode/U+002D

可能只需要将字符串的末尾扩展到参数之后。
要涵盖有参数和无参数可能是:

^(/[a-z0–9/_-]*(?<!/))([^/]*)$ -> /

https://regex101.com/r/Iwl23o/2

您可以按照以下方式进行:

public class Main {
    public static void main(final String[] args) {
        String[] arr = { "/news", "/news?param1=value1", "/news#anchor?param1=value1" };
        for (String s : arr) {
            System.out.println(s.replaceFirst("([^\/\p{Punct}]+)", "/"));
        }
    }
}

输出:

/news/
/news/?param1=value1
/news/#anchor?param1=value1

正则表达式的解释:

您可以像这样使用非常简单的正则表达式:

^([/\w]+)

使用此替换字符串:/

Working demo