獲取和替換#{}中的內容

package StringTest;

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

public class Test {
    public static void main(String[] args) {
        String str = "select * from emp where name = #{name} and id = #{id}";

        //獲取以 #{ 開始,不是 } 結尾的多個字符 (其中()用來分組)
        Pattern p = Pattern.compile("#\\{([^}]+)");
        Matcher m = p.matcher(str);

        //獲取 #{} 中的內容
        while (m.find()){
            System.out.println(m.group(1));
        }

        //替換#{xxx},其中xxx是參數
        str = str.replaceAll("#\\{[^}]+\\}","?");
        System.out.println(str);
    }
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章