查找是否包含字串 查询是否包含 #{name} 片段 这里有包含所以返回true
String context = "select * from t_user where (name = #{name} or username = #{name}) and age > #{age}"; String regex = ".*#\\{name\\}.*"; boolean is = Pattern.matches(regex,context);
匹配所有 #{任何内容}
String context = "select * from t_user where (name = #{name} or username = #{name}) and age > #{age}"; //String regex = "\\{([^}]*)\\}"; String regex = "#\\{(.*?)\\}"; //创建 Pattern 对象 Pattern r = Pattern.compile(regex); //创建 Matcher 对象 Matcher m = r.matcher(context); while (m.find()){ System.out.println(m.group() + "=" + m.group(1)); }
输出内容为
#{name}=name #{name}=name #{age}=age
匹配和替换
Map<String,Object> param = new HashMap<>(); param.put("name","张三"); param.put("age",28); String context = "select * from t_user where (name = #{name} or username = #{name}) and age > #{age}"; //String regex = "\\{([^}]*)\\}"; String regex = "#\\{(.*?)\\}"; System.out.println(regex); //创建 Pattern 对象 Pattern r = Pattern.compile(regex); //创建 Matcher 对象 Matcher m = r.matcher(context); StringBuffer sb = new StringBuffer(); int i = 0; Map<Integer,Object> params = new HashMap<>(); while (m.find()){ i++; System.out.println(m.group() + "=" + m.group(1)); m.appendReplacement(sb,"?"); params.put(i,param.get(m.group(1))); } m.appendTail(sb); System.out.println(sb);//select * from t_user where (name = ? or username = ?) and age > ? System.out.println(params);//{1=张三, 2=张三, 3=28}