java中替換${xx}


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class replace {

    public static void main(String[] args) {
     Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
      Matcher m = p.matcher("one cat ${two} cats in the yard");
      StringBuffer sb = new StringBuffer();
      while (m.find()) {
          String group = m.group(2);//規則中${值}中的 值 一樣 的數據不
          System.out.println("符合規則中第二個的值"+group);
          //下一步是替換並且把替換好的值放到sb中
          m.appendReplacement(sb, "dog");
      }
      //把符合的數據追加到sb尾
      m.appendTail(sb);
      System.out.println(sb.toString());


     下邊是從其他人的理解
     https://www.cnblogs.com/jsStudyjj/p/6145623.html
String str
= "Hello,World! in Java."; Pattern pattern = Pattern.compile("W(or)(ld!)"); Matcher matcher = pattern.matcher(str); while(matcher.find()){ System.out.println("Group 0:"+matcher.group(0));//得到第0組——整個匹配 System.out.println("Group 1:"+matcher.group(1));//得到第一組匹配——與(or)匹配的,str中有和我的規則中的第一個括號中的數據一樣的 System.out.println("Group 2:"+matcher.group(2));//得到第二組匹配——與(ld!)匹配的,組也就是子表達式,str中有和我的規則中的第二個括號中的數據一樣的 System.out.println("Start 0:"+matcher.start(0)+" End 0:"+matcher.end(0));//總匹配的索引 System.out.println("Start 1:"+matcher.start(1)+" End 1:"+matcher.end(1));//第一組匹配的索引 System.out.println("Start 2:"+matcher.start(2)+" End 2:"+matcher.end(2));//第二組匹配的索引 System.out.println(str.substring(matcher.start(0),matcher.end(1)));//從總匹配開始索引到第1組匹配的結束索引之間子串——Wor } } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM