java regular expression find and replace

后端 未结 7 2139
执念已碎
执念已碎 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:02

    Hopefully you would find this code useful:

        Pattern phone = Pattern.compile("\\$\\{env([0-9]+)\\}");
        String line ="${env1}sojods${env2}${env3}";
        Matcher action = phone.matcher(line);
        StringBuffer sb = new StringBuffer(line.length());
        while (action.find()) {
          String text = action.group(1);
          action.appendReplacement(sb, Matcher.quoteReplacement(text));
        }
        action.appendTail(sb);
        System.out.println(sb.toString());
    

    The output is the expected: 1sojods23.

提交回复
热议问题