0

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;
}

3 Answers 3

1
  • Consider Pattern.quote if text can contain regex metacharacters.
  • Consider java.util.Scanner and findWithinHorizon
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.