我需要你的帮助来在Java中编写一个与某些文本中的单词匹配的正则表达式,我需要返回所有存在正确匹配的行。每一行都存在于HashMap中。我打电话找到" var",我试着写一些例子:
我尝试编写此代码,但它不起作用,因为它匹配表达式,如" var Text",不必匹配:
public static void coinvolgimento_variabile(HashMap<Integer, String> tokens, String var) {
var = var.trim();
String pattern_var = "\\W*\\D*\\s*"+var+"\\s*\\D*\\W*";
String not_pattern1 = "\\w+"+var+".*?";
String not_pattern2 = ".*?"+var+"\\w+";
Pattern p = Pattern.compile(pattern_var, Pattern.CASE_INSENSITIVE);
Pattern p1 = Pattern.compile(not_pattern1, Pattern.CASE_INSENSITIVE);
Pattern p2 = Pattern.compile(not_pattern2, Pattern.CASE_INSENSITIVE);
Matcher m, m1, m2;
for(int i=0; i<tokens.size(); i++) {
m = p.matcher(tokens.get(i));
m1 = p1.matcher(tokens.get(i));
m2 = p2.matcher(tokens.get(i));
if(m.matches()==true && m1.matches()==false && m2.matches()==false) {
System.out.println("Trovata var "+var+": "+tokens.get(i));
}
}
System.out.println("\n\n\n\n\n");
}