5

我正在使用 bufferedreader 读取文件,所以可以说我有

line = br.readLine();

我想检查这一行是否包含许多可能的字符串之一(我在一个数组中)。我希望能够写出类似的东西:

while (!line.matches(stringArray) { // not sure how to write this conditional
  do something here;
  br.readLine();
}

我对编程和Java相当陌生,我是否以正确的方式进行?

4

3 回答 3

3

将所有值复制到 a 中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
    ...
}

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

于 2009-11-04T08:42:49.607 回答
2

这取决于是什么stringArray。如果是的Collection话就好了。如果它是一个真正的数组,则应将其设为Collection. 该Collection接口有一个调用方法,该方法contains()将确定给定Object对象是否在Collection.

将数组转换为 的简单方法Collection

String tokens[] = { ... }
List<String> list = Arrays.asList(tokens);

a 的问题List是查找很昂贵(技术上是线性的或O(n))。更好的选择是使用 a Set,它是无序的,但具有近乎恒定的 ( O(1)) 查找。您可以像这样构建一个:

从一个Collection

Set<String> set = new HashSet<String>(stringList);

从数组:

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

然后set.contains(line)将是一个廉价的操作。

编辑:好的,我认为你的问题不清楚。您想查看该行是否包含数组中的任何单词。你想要的是这样的:

BufferedReader in = null;
Set<String> words = ... // construct this as per above
try {
  in = ...
  while ((String line = in.readLine()) != null) {
    for (String word : words) {
      if (line.contains(word)) [
        // do whatever
      }
    }
  }
} catch (Exception e) {
  e.printStackTrace();
} finally {
  if (in != null) { try { in.close(); } catch (Exception e) { } }
}

这是一个相当粗略的检查,它的使用出奇地开放,并且往往会在诸如“废品”之类的词上给出令人讨厌的误报。对于更复杂的解决方案,您可能必须使用正则表达式并查找单词边界:

Pattern p = Pattern.compile("(?<=\\b)" + word + "(?=\b)");
Matcher m = p.matcher(line);
if (m.find() {
  // word found
}

您可能希望更有效地执行此操作(例如不编译每一行的模式),但这是使用的基本工具。

于 2009-11-04T08:50:06.387 回答
0

使用该String.matches(regex)函数,如何创建一个匹配字符串数组中任何一个字符串的正则表达式?就像是

String regex = "*(";
for(int i; i < array.length-1; ++i)
  regex += array[i] + "|";
regex += array[array.length] + ")*";
while( line.matches(regex) )
{
  //. . . 
}
于 2009-11-04T08:53:08.790 回答