Positioning regexes with anchors
In many cases, a regex has to be applied to the string in such a way that its beginning coincides with the beginning of the string. For example, if a phone number contains the +
character, it can only appear in the first position.
Perl 6 regexes have so-called anchors—special characters, that anchor a regex to either the beginning or the end of the string or a logical line.
Matching at the start and at the end of lines or strings
Let us modify the phone number regex so that it forces the regex to match with the whole string containing a potential phone number:
/ ^ \+? <[\d\s\-]>+ $ /;
Here, ^
is the anchor that matches at the beginning of the string and does not consume any characters. On the other side of the regex, $
requires that the end of the regex matches the end of the string. So, a valid phone number, say +49 20 102-14-25
will pass the filter, while a mathematical expression such as 124 + 35 - 36
will not.
For better visibility, anchors can be written...