java regular expression find and replace

后端 未结 7 2138
执念已碎
执念已碎 2020-12-14 21:37

I am trying to find environment variables in input and replace them with values.

The pattern of env variable is ${\\\\.}

Pattern myPatte         


        
7条回答
  •  佛祖请我去吃肉
    2020-12-14 22:08

    Strings in Java are immutable, which makes this somewhat tricky if you are talking about an arbitrary number of things you need to find and replace.

    Specifically you need to define your replacements in a Map, use a StringBuilder (before Java 9, less performant StringBuffer should have been used) and the appendReplacements() and appendTail() methods from Matcher. The final result will be stored in your StringBuilder (or StringBuffer).

    Map replacements = new HashMap() {{
        put("${env1}", "1");
        put("${env2}", "2");
        put("${env3}", "3");
    }};
    
    String line ="${env1}sojods${env2}${env3}";
    String rx = "(\\$\\{[^}]+\\})";
    
    StringBuilder sb = new StringBuilder(); //use StringBuffer before Java 9
    Pattern p = Pattern.compile(rx);
    Matcher m = p.matcher(line);
    
    while (m.find())
    {
        // Avoids throwing a NullPointerException in the case that you
        // Don't have a replacement defined in the map for the match
        String repString = replacements.get(m.group(1));
        if (repString != null)    
            m.appendReplacement(sb, repString);
    }
    m.appendTail(sb);
    
    System.out.println(sb.toString());
    

    Output:

    1sojods23
    

提交回复
热议问题