Reputation: 497
I need to parse through a file(built from a string) searching for occurences of a single or multiline text. Will this solution always work ? If not - how should I change it ?
private int parseString(String s){
Pattern p = Pattern.compile(searchableText);
Matcher m = p.matcher(s);
int count = 0;
while(m.find()) {
count++;
}
return count;
}
Upvotes: 0
Views: 210
Reputation:
Consider searching for a\s+b\s+c\s+
where a
, b
, and c
are the sequence of words (or characters if you wish) you are searching for. It may be (over) greedy, but hopefully it should give an insight. You can also perform a normalization of the text first.
Upvotes: 0
Reputation: 262504
For multiline strings you need to adjust the newline codes to what is the file, or (probably better) use a regular expression to be able to accept all the various combinations of \n and \r.
Upvotes: 0
Reputation: 383746
Pattern.quote
if text can contain regex metacharacters.java.util.Scanner
and findWithinHorizon
Upvotes: 1