mastodon
mastodon

Reputation: 497

Java regex matching

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

Answers (3)

user166390
user166390

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

Thilo
Thilo

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

polygenelubricants
polygenelubricants

Reputation: 383746

  • Consider Pattern.quote if text can contain regex metacharacters.
  • Consider java.util.Scanner and findWithinHorizon

Upvotes: 1

Related Questions