Java正则表达式未正确替换
下面是我想替换几个字符串的代码片段。我在代码中的两个地方使用了date_add模式,但它只被替换了一次。我正在使用字符串。但对我来说还是不行。请帮我查明原因
public class Implementation {
public static void main(String[] args) {
String ipquery = "select to_date(id) from location_dim location_dim where ( location_name = '123' ) limit 10 union all select item_id " +
"item_id from (select item_dim.time_id from item_dim item_dim where item_dim.time_id in ( select time_dim.id from time_dim " +
"where (( time_dim . day ) = date_add( '1999-01-01' , 2 )) ) ) item_dim inner join time_dim time_dim on (( item_dim . time_id ) " +
"= ( time_dim . id )) where (( time_dim . day ) = date_add( '1999-01-01' , 2 )) limit 20";
System.out.println(replace(ipquery));
}
public static String replace(String query) {
Map<String, String> imputnmatch = new HashMap<String, String>();
imputnmatch.put("to_date", "date");
imputnmatch.put("format_number", "format");
imputnmatch.put("date_sub\\((.*),\\s*([0-9]+\\s*)\\)",
"date_sub($1, interval $2 day)");
imputnmatch.put("date_add\\((.*),\\s*([0-9]+\\s*)\\)",
"date_add($1, interval $2 day)");
for (Map.Entry<String, String> entry : imputnmatch.entrySet()) {
query = query.replaceAll(entry.getKey(), entry.getValue());
System.out.println(entry.getKey() + " " + entry.getValue() + " " +query);
}
return query;
}
}
# 1 楼答案
在
"date_add\\((.*),\\s*([0-9]+\\s*)\\)"
模式中.*
将尝试找到最大的潜在匹配,因此它将尝试找到以date_add\\(
开始并以,\\s*([0-9]+\\s*)\\)
结束的部分,这意味着在数据中它会匹配的
要使
.*
搜索最小匹配,需要在*
量词后面添加?
使*
量词不情愿(lazy)。所以试试看同样的规则适用于
date_sub\\((.*),\\s*([0-9]+\\s*)\\)
模式,这意味着您需要将其更改为date_sub\\((.*?),\\s*([0-9]+\\s*)\\)
# 2 楼答案
您正在使用。*这也包括“)”所以你的一个日期子是包含在日期子模式中的。所以,改变你的约会时间;日期添加模式It will help you