搜索字符串中特殊字符之间的子字符串

时间:2011-12-16 13:40:37

标签: java regex string replace

我有一个像

这样的字符串
(&(objectclass=${abc})(uid=${xyz}))

如何搜索 $ {abc} $ {xyz} 并替换为其他字符串。这些子串中可能有任意数量的出现,即主字符串中的$ {abc}。我在考虑string.indexOf(,但这可能会很混乱。有什么最好的方法吗?

$ {abc}将被另一个字符串abc替换。我将从其他一些参数中获取它们。

4 个答案:

答案 0 :(得分:2)

您需要转义特殊字符(${})。试试这个:

str.replaceAll("\\$\\{abc\\}","abc");

这可能很奇怪,但可以帮助你:

str = str.substring(str.indexOf("${")+2, str.indexOf("}"))

这适用于${}之间的所有(任意数量)字符串。

答案 1 :(得分:1)

我会在循环中重复使用String.indexOf(String sep, int start)来将文本和值复制到StringBuilder。


这样的东西
public static void main(String... args) throws IOException {
    Map<String, String> map = new LinkedHashMap<>();
    map.put("abc", "ABC");
    map.put("xyz", "XYZ");
    printSubstitue("nothing to change", map);
    printSubstitue("(&(objectclass=${abc})(uid=${xyz})(cn=${cn})(special='${'))", map);
}

private static void printSubstitue(String text, Map<String, String> map) {
    String text2 = subtitue(text, map);
    System.out.println("substitue( "+text+", "+map+" ) = "+text2);
}

public static String subtitue(String template, Map<String, String> map) {
    StringBuilder sb = new StringBuilder();
    int prev = 0;
    for (int start, end; (start = template.indexOf("${", prev)) > 0; prev = end + 1) {
        sb.append(template.substring(prev, start));
        end = template.indexOf('}', start + 2);
        if (end < 0) {
            prev = start;
            break;
        }
        String key = template.substring(start + 2, end);
        String value = map.get(key);
        if (value == null) {
            sb.append(template.substring(start, end + 1));
        } else {
            sb.append(value);
        }

    }
    sb.append(template.substring(prev));
    return sb.toString();
}

打印

substitue( nothing to change, {abc=ABC, xyz=XYZ} ) = nothing to change
substitue( (&(objectclass=${abc})(uid=${xyz})(cn=${cn})(special='${')), {abc=ABC, xyz=XYZ} ) 
     = (&(objectclass=ABC)(uid=XYZ)(cn=${cn})(special='${'))

如果要支持嵌套的${ }值,则会变得混乱。 ;)

abc123=ghi123
abc${xyz}=def${xyz}

(&(objectclass=${abc${xyz}})(uid=${xyz}))

如果可以的话,我建议你保持简单。 ;)

答案 2 :(得分:0)

你需要的正则表达式是\$\{[^}]+\}。用必要的东西替换。

编辑:好的,我误解了这个问题。正则表达式已修复。

答案 3 :(得分:0)

像这样的正则表达式有效:

String regex = "(\\$\\{YOUR_TOKEN_HERE\\})";

以下是一个使用示例:

public static void main(String[] args) throws Exception {
    String[] lines = {
        "(&(objectclass=${abc})(uid=${xyz}))",
        "(&(objectclass=${abc})(uid=${xyz})(xyz=${xyz})(abc=${abc}))"
    };

    String token = "abc"; // or whatever

    String regex = String.format("(\\$\\{%s\\})", token);
    Pattern p = Pattern.compile(regex);
    for (String s: lines) {
        Matcher m = p.matcher(s);
        if (m.find()) {
            System.err.println(m.replaceAll("###"));
        }
    }
}

令牌的输出=&#34; abc&#34;是:

(&(objectclass=###)(uid=${xyz}))
(&(objectclass=###)(uid=${xyz})(xyz=${xyz})(abc=###))