【问题标题】:java regex add trailing slashjava正则表达式添加斜杠
【发布时间】:2020-07-02 16:59:31
【问题描述】:

我正在尝试重定向网址以添加斜杠

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

我需要通过一个仅标识路径并添加 / 的正则表达式来执行此操作。没有参数就没有问题。

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

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

有什么想法吗,谢谢

【问题讨论】:

  • 正则表达式中的 $ 匹配输入的结尾(或多行模式下的一行),因此它不会匹配任何带有路径参数的 url。

标签: java regex magnolia


【解决方案1】:

可能只需要将字符串的结尾扩展到参数之外。
涵盖带参数和不带参数的可能是:

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

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

【讨论】:

  • 它工作得很好,我只是补充说它也接受大写字母。非常感谢,我已经被这个问题发疯了。
【解决方案2】:

你不应该将字符串的结尾与$ 匹配,也不需要[^/]

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

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

【讨论】:

    【解决方案3】:

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

    ^([/\w]+)
    

    使用此替换字符串:$1/

    Working demo

    【讨论】:

      【解决方案4】:

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

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


      您可以重复 1 次或多次匹配正斜杠,然后重复 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("$0/");
      
      System.out.println(result);
      

      输出

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

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

      https://www.compart.com/en/unicode/U+2013 而不是https://www.compart.com/en/unicode/U+002D

      【讨论】:

        【解决方案5】:

        你可以这样做:

        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}]+)", "$1/"));
                }
            }
        }
        

        输出:

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

        正则表达式的解释:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-05
          • 2013-01-28
          • 1970-01-01
          • 1970-01-01
          • 2015-03-15
          • 2011-03-09
          • 1970-01-01
          相关资源
          最近更新 更多