Anchors and bounds allow us to identify special positions within a string of text.
They do not match characters themselves, but rather indicate the position where a match should occur.
- Anchors allow locating the start and end of a line or string
- Bounds allow locating the start and end of words
Start and End Anchors
The anchors ^
and $
are very useful for validating strings that must start or end with certain characters.
The two most common anchors are:
Symbol | Description |
---|---|
^ | Indicates the start of a line or string |
$ | Indicates the end of a line or string |
For example, if we want to find strings that start with “Hello”, we use ^
:
But this Hello won't be found
While if we want to find strings that end with “goodbye”, we use $
:
How to Use Bounds in Regex
Bounds are similar to anchors, but they are used to define positions relative to characters.
The most common bounds are:
Symbol | Description |
---|---|
\b | Represents a word boundary |
\B | Represents a non-word boundary |
Word boundaries \b
are useful to ensure that we are matching complete words and not as part of others.
For example, if we want to find the word “house” without it being part of another word, we use:
In this example,
- It found the word “house”
- But avoided the string “house” that is within “houseable”
While if we want to find the sequence ou
in the word “house”, we can use \B
:
In this case,
- It finds the match for “ou” within “house”
- But does not find the “ou” at the end of “you”