想利用java里pattern功能处理对多个关键字的匹配查询
例如Patternpattern=Pattern.compile("切");Matchermatcher=pattern.matcher(txt);while(match...
例如
Pattern pattern = Pattern.compile("切");
Matcher matcher = pattern.matcher(txt);
while (matcher.find()) {
String msg = ":" + matcher.group() + ":";
System.out.println(msg);
}
程序会从txt中把“切”提取出来,可是我不仅相提切,还想提取蒸煮炖炸等多个关键词,怎么办?
谢谢 展开
Pattern pattern = Pattern.compile("切");
Matcher matcher = pattern.matcher(txt);
while (matcher.find()) {
String msg = ":" + matcher.group() + ":";
System.out.println(msg);
}
程序会从txt中把“切”提取出来,可是我不仅相提切,还想提取蒸煮炖炸等多个关键词,怎么办?
谢谢 展开
2个回答
展开全部
Pattern pattern = Pattern.compile("切");
Matcher matcher = pattern.matcher(txt);
Matcher matcher2 = Pattern.compile("蒸").matcher(txt);
Matcher matcher3 = Pattern.compile("煮").matcher(txt);
Matcher matcher4 = Pattern.compile("炖").matcher(txt);
Matcher matcher5 = Pattern.compile("炸").matcher(txt);
boolean a = false;
boolean b = false;
boolean c = false;
boolean d = false;
boolean e = false;
while ((a = matcher.find())|| (b = matcher2.find())||(c = matcher3.find())||( d = matcher4.find())||(e = matcher5.find())) {
String msg ="";
if(a){
msg = ":" + matcher.group() + ":";
}else if(b){
msg = ":" + matcher2.group() + ":";
}else if(c){
msg = ":" + matcher3.group() + ":";
}else if(d){
msg = ":" + matcher4.group() + ":";
}else if(e){
msg = ":" + matcher5.group() + ":";
}
System.out.println(msg);
}
只不过这样比较麻烦,你可以自己精炼下,我想知道,你提取关键字是不是只是想确定是否包含,如果是你可以不用这个方法
Matcher matcher = pattern.matcher(txt);
Matcher matcher2 = Pattern.compile("蒸").matcher(txt);
Matcher matcher3 = Pattern.compile("煮").matcher(txt);
Matcher matcher4 = Pattern.compile("炖").matcher(txt);
Matcher matcher5 = Pattern.compile("炸").matcher(txt);
boolean a = false;
boolean b = false;
boolean c = false;
boolean d = false;
boolean e = false;
while ((a = matcher.find())|| (b = matcher2.find())||(c = matcher3.find())||( d = matcher4.find())||(e = matcher5.find())) {
String msg ="";
if(a){
msg = ":" + matcher.group() + ":";
}else if(b){
msg = ":" + matcher2.group() + ":";
}else if(c){
msg = ":" + matcher3.group() + ":";
}else if(d){
msg = ":" + matcher4.group() + ":";
}else if(e){
msg = ":" + matcher5.group() + ":";
}
System.out.println(msg);
}
只不过这样比较麻烦,你可以自己精炼下,我想知道,你提取关键字是不是只是想确定是否包含,如果是你可以不用这个方法
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询