我正在使用 bufferedreader 读取文件,所以假设我有
line = br.readLine();
我想检查这一行是否包含许多可能的字符串之一(我在一个数组中)。我希望能够写出类似的东西:
while (!line.matches(stringArray) { // not sure how to write this conditional
do something here;
br.readLine();
}
我是编程和 Java 的新手,我的做法是否正确?
最佳答案
将所有值复制到 Set<String>
中然后使用 contains()
:
Set<String> set = new HashSet<String> (Arrays.asList (stringArray));
while (!set.contains(line)) { ... }
[编辑] 如果您想知道行的一部分是否包含集合中的字符串,您必须遍历集合。替换 set.contains(line)
调用:
public boolean matches(Set<String> 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
...
}
如果数组中有很多元素,这会更便宜,因为正则表达式代码会优化匹配过程。
关于java - 将数组与java中的字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1672416/