天天看点

java 匹配字符串数组_在java中匹配数组与字符串

将所有值复制到Set< String>然后使用contains():

Set set = new HashSet (Arrays.asList (stringArray));

while (!set.contains(line)) { ... }

[编辑]如果要查明该行的一部分是否包含该集合中的字符串,则必须循环该集合.将set.contains(line)替换为:

public boolean matches(Set set, String line) {

for (String check: set) {

if (line.contains(check)) return true;

}

return false;

}

使用正则表达式或更复杂的匹配方法时,请相应地调整检查.

[EDIT2]第三个选项是在一个巨大的正则表达式中连接数组中的元素|:

Pattern p = Pattern.compile("str1|str2|str3");

while (!p.matcher(line).find()) { // or matches for a whole-string match

...

}

如果数组中有许多元素,这可能会更便宜,因为正则表达式代码将优化匹配过程.