Describes purpose and use of anchor metacharacters.
When you use the contains function, it returns true if the regular expression matched anywhere in the string. However, sometimes you would like to specify where in the string the regular expression should try to match. To do this, you use anchor metacharacters.
display "rock and roll".contains('/and/')
// displays true
display "rock and roll".contains('/~np~^~/np~and/')
// displays false
display "rock and roll".contains('/~np~^~/np~rock/')
// true
display "rock and roll".contains('/rock$/')
// false
display "rock and roll".contains('/roll$/')
// true
display "rock and roll".contains('/nd roll$/')
// true
display "rock and roll".contains('/\~np~^~/np~rock$/')
// false
display "rock and roll".contains('/\~np~^~/np~rock and roll$/')
// true
display "rock and roll".isMatch('/rock and roll/')
// true
The second regular expression does not match because '^' constrains and to match only if it is at the beginning of the string. The fifth regular expression does match, since the '$' constrains roll to match only at the end of the string.
Look at the last two examples. If you use both the '^' and '$', you mean that the regular expression must match both the beginning and the end of the string. In other words, the regular expression matches the whole string. Note that both examples are equivalent since the isMatch will always look for a complete match. The '^' and '$' anchors are irrelevant when using isMatch.
display "rock and~np~\~/np~nroll".contains('/and$/m')
// true
display "rock and~np~\~/np~nroll".contains('/and~np~\~/np~Z/m')
// false
display "rock and~np~\~/np~nroll".contains('/^roll$/')
// true
display "rock and~np~\~/np~nroll".contains('/~np~\~/np~Aroll~np~\~/np~Z/')
// false
display "rock and~np~\~/np~nroll".contains('/~np~\~/np~Arock/')
// true
| Modifier | Behavior |
|---|---|
| none | Default behavior. '.' matches any character except '\n'. '^' only matches at the beginning of the string and '$' only matches at the end of the string. |
| s | Treat string as a single long line. '.' matches any character, even '\n'. '^' only matches at the beginning of the string and '$' only matches at the end or before a new line at the end. |
| m | Treat string as a set of multiple lines. '.' matches any character except '\n'. '^' and '$' are able to match at the start or end of any line within the string. |
| m and s | Treat string as a single long line but detect multiple lines. '.' matches any character, even '\n', '^', and '$'. However, they are able to match at the start or at the end of any line within the string. |