views:

44

answers:

3

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;
}
+1  A: 
  • Consider Pattern.quote if text can contain regex metacharacters.
  • Consider java.util.Scanner and findWithinHorizon
polygenelubricants
A: 

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.

Thilo
have you seen regex of this sort somewhere already made ?
owca
A: 

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.

pst