Counting occurrences
Documentation for version: 0.41.2
In certain situations an amount of occurrences is desired, but not the occurrences themselves.
In that case, it's recommended to consider Pattern.count(), instead of performing full matches
with Matcher.all()/Search.all().
Method Pattern.count() accepts a string subject, and returns the number of occurrences of
the pattern in the subject.
Unmatched subjects#
When Pattern.count() is called with a subject that doesn't match the pattern,
then count() returns 0.
Malformed patterns#
Every use of pattern()/Pattern::of() with an invalid pattern causes MalformedPatternException.
Number of occurrences in Matcher#
Apart from Pattern.count(), methods Matcher.count() and Search.count() can also be used to
retrieve the number of occurrences of the pattern in the subject.
Additionally, Matcher implements PHP interface \Countable, and so can be used with PHP methods,
such as count():
Performance predicating a subject#
It might appear suitable to use count() to ascertain whether a given subject matches the
pattern, since count() doesn't return any matches.
While that is true, that using Pattern.count() is more performant than Matcher.all(),
it still iterates all of the occurrences of the pattern in the subject.
The recommended approach for such predication is with test()/fails():
That's because count() goes through each occurrence of a pattern in the subject counting it,
whereas test() returns right after matching the first occurrence.