开发者

search for multiple strings in a file in java

开发者 https://www.devze.com 2023-02-26 15:34 出处:网络
String[] searchText = {\"sports\",\"football\",\"play\",\"time\"}; 开发者_如何学Gohow can i search if these words are available in a fileThis should work (given some String s, that represents the docu

String[] searchText = {"sports","football","play","time"}; 开发者_如何学Gohow can i search if these words are available in a file


This should work (given some String s, that represents the document)

Pattern p = Pattern.compile("(sports|football|play|time)");
Matcher m = p.matcher(s);

int start = 0;
while (m.find(start)) {
    System.out.println("Match found: " + m.group(1) + " at position: " + m.start());
    start = m.end();
}


You can either do it in a brute force manner by reading the file line by line and check each one to see if one or more of the words in the array appear.

Or you can do something more elegant with Lucene and indexing. This would be a better idea if you really want to do searches where the words you're interested in change frequently.


Simplest way to do it: do a linear search on the file:

  1. Open the file
  2. Parse it by word
  3. While parsing, check if word is present in your list

A more efficient but complicated approach would be writing a program the computes a text-index on the file and use that index to search for the words.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号