【问题标题】:Wildcard match and replace in JavaJava中的通配符匹配和替换
【发布时间】:2017-10-12 19:42:30
【问题描述】:

我想检查一个字符串以查看它是否包含 $wildcard$,并且仅当它包含时,我才想提取“$ $”之间的值,我将使用它来检索替换。然后替换完整的新字符串(同时删除 $ $)

编辑:设法让这个工作demo

String subject = "test/$name$/something";
String replace = "foo_bar";
Pattern regex = Pattern.compile("(\\$).*?(\\$)");
Matcher m = regex.matcher(subject);

StringBuffer b= new StringBuffer();
while (m.find()) {
     String something = m.group(0);
     System.out.println(something);
     m.appendReplacement(b, replace);
}
m.appendTail(b);
String replaced = b.toString();
System.out.println(replaced);

给我输出

$name$
test/foo_bar/something

我可以使用子字符串来删除前导/尾随 $ 但有没有办法将它们分成组,这样我就可以得到 $ $ 之间的内容。但还要确保初始检查确保它有一个开始和结束 $

【问题讨论】:

标签: java regex wildcard


【解决方案1】:

为标签内容添加另一个匹配组:

Pattern.compile("(\\$)(.*?)(\\$)");

【讨论】:

    【解决方案2】:

    \\$ 中删除不必要的捕获组,将捕获组设置为匹配两个$ 字符之间的模式(这里使用的最有效的构造是否定字符类[^$]),以及然后直接获取.group(1)的值:

    String subject = "test/$name$/something";
    String replace = "foo_bar";
    Pattern regex = Pattern.compile("\\$([^$]*)\\$"); // ONLY 1 GROUP ROUND [^$]*
    Matcher m = regex.matcher(subject);
    StringBuffer b= new StringBuffer();
    while (m.find()) {
        String something = m.group(1); // ACCESS GROUP 1
        System.out.println(something);
        m.appendReplacement(b, replace);
    }
    m.appendTail(b);
    String replaced = b.toString();
    System.out.println(replaced);
    

    Java demo

    结果:

    name
    test/foo_bar/something
    

    模式详情

    • \\$ - 一个 $ 字符
    • ([^$]*) - Capturing group 1 匹配除$ char 之外的零个或多个字符
    • \\$ - $ 字符。

    【讨论】:

      【解决方案3】:

      它具有您所要求的略微不同的语法,但请查看 Apache Commons Text:https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StrSubstitutor.html

      这将让您执行以下操作:

          Map<String,String> substitutions = ImmutableMap.of("name", "foo_bar");
          String template = "/test/${name}/something";
          StrSubstitutor substitutor = new StrSubstitutor(substitutions);
          System.out.println(substitutor.replace(template));
      

      您可以构建自己的地图来填充您的替换值。

      【讨论】:

      • 看起来是一个有趣的替代方案,但它是从其他人可以 $$ 模式读取的配置文件中读取的。所以我不会总是知道他们之间是什么。任何添加都需要更改代码
      猜你喜欢
      • 1970-01-01
      • 2014-08-14
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多