All the examples so far have recognized patterns anywhere in a string. But you may want the patterns to match only if they, for example, appear at the beginning of the string. Anchors provide that capability.
Anchors allow you to fix a Regular Expression to either the beginning or end of a string. They also allow you to create Regular Expressions that occur either within a word or at the beginning or end of a word. The following table contains the list of Regular Expression anchors and their meanings:
Character |
Description |
|
Matches the position at the beginning of the input string. If the multi-line property is set, |
|
Matches the position at the end of the input string. If the multi-line property is set, |
|
Matches a word boundary, that is, the position between a word and a space. |
|
Matches a non-word boundary. |
You cannot use a quantifier with an anchor. Since you cannot have more than one position immediately before or after a newline or word boundary, expressions such as ^* are not permitted.
To match text at the beginning of a line of text, use the ^ character at the beginning of the Regular Expression. This is different from using the ^ within a bracket expression.
To match text at the end of a line of text, use the $ character at the end of the Regular Expression.
To use anchors when searching for chapter headings, the following regular expression matches a chapter heading with up to two following digits that occur at the beginning of a line and where there is no text after the heading:
/^Chapter [1-9][0-9]?$/Matching word boundaries is a little different but adds a very important capability to Regular Expressions. A word boundary is the position between a word and a space. A non-word boundary is any other position. The following regular expression matches the first three characters of the word 'Chapter' because they appear following a word boundary:
/\bCha/The position of the '\b' operator is critical here. If it's positioned at the beginning of a string to be matched, it looks for the match at the beginning of the word; if it's positioned at the end of the string, it looks for the match at the end of the word. For example, the following expressions match 'ter' in the word 'Chapter' because it appears before a word boundary:
/ter\b/