Optional matches (Find first)
If you call first()
on a subject that isn't matched by a pattern - SubjectNotMatchedException
is
thrown. We discussed that in the previous chapter.
But what if you expected the subject not to be matched? And how do you to react to it?
findFirst()
#
Optional matches with Method findFirst()
can be called with a callback (that accepts Detail
) just like first()
.
The difference is: findFirst()
never throws SubjectNotMatchedException
, and allows you to control an unmatched subject by
appropriate control methods: orThrow()
, orReturn()
and orElse()
.
For example:
- T-Regx
- PHP
If a match is found, then the result of findFirst()
callback is returned. If a match is not found, however, then the
handling of an unmatched subject lies in the chained method.
orReturn()
#
If a match is not found, it returns a default value.
- T-Regx
- PHP
orElse()
#
If a match is not found, it calls orElse()
callback and uses it to evaluate a return value.
- T-Regx
- PHP
orThrow()
#
Returns the optional value, or throws the specified exception.
- T-Regx
- PHP