search for multiple strings in a file in java
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:
- Open the file
- Parse it by word
- 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.
精彩评论