-
Notifications
You must be signed in to change notification settings - Fork 0
Assertions
Assertions are tests on patterns that does not actually consume any characters. In REBuilder assertions are instances of REBuilder\Pattern\Assertion
class and can be added using addAssertion
.
There are two types of assertions that can be defined by the first argument of addAssertion
or assertions class constructor:
- Lookahead: this assertion analyze everything that comes after the current point ad must be added after a pattern.
- Lookbehind: this assertion analyze everything that comes before the current point ad must be added before a pattern.
For example to match "a" only if it is followed by "b" you must create a lookahead assertion:
$regex
->addCharAndContinue("a")
->addAssertion()
->addChar("b");
echo $regex; // "/a(?=b)/"
If you want to match "a" only if it comes after "b" you must create a lookbehind assertion:
$regex
->addAssertion(false)
->addCharAndContinue("b")
->getParent()
->addChar("a");
echo $regex; // "/(?<=b)a/"
The second boolean argument indicates (if true) if the test must be negative, so it will match only if the pattern does not preceed (lookahead) or does not follow (lookbehind) the patterns in the assertion.
There are also some simple assertions you can use in your regex. In REBuilder they are instances of REBuilder\Pattern\SimpleAssertion
and can be added using addSimpleAssertion
or addSimpleAssertionAndContinue
.
Some examples of these assertions are (for a complete list refer to PHP documentation):
- \b: word boundary
- \B: not a word boundary
- \A: start of subject
For example to match "a" only if it is a word boundary:
$regex
->addSimpleAssertionAndContinue("b")
->addChar("a");
echo $regex; // "/\ba/"
Note that only valid simple assertions identifiers can be provided, an invalid identifiers throws an exception.