Anchors and boundaries allow us to identify special positions within a text string.
They do not match characters themselves, but indicate the position where a match must occur.
- Anchors allow locating the beginning and end of a line or string
- Boundaries allow locating the beginning and end of a word
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 beginning of a line or string |
$ | Indicates the end of a line or string |
For example, if we want to find strings that start with “Hola”, we use ^:
Pero este Hola no lo va a encontrar
While if we want to find strings that end with “adiós”, we use $:
How to Use Boundaries in Regex
Boundaries are similar to anchors, but are used to define positions in relation to characters.
The most common boundaries are:
| Symbol | Description |
|---|---|
\b | Represents a word boundary |
\B | Represents a non-word boundary |
Word boundaries \b are useful to ensure we are matching whole words and not parts of other words.
For example, if we want to find the word “casa” without it being part of another word, we use:
In this example,
- It found the word “casa”
- But it avoided the string “casa” that is inside “casadera”
While if we want to find the sequence ou within the word “casa”, we can use \B:
In this case,
- It finds the match for “as” inside “casa”
- But it does not find the “as” at the end of “mas”
