regex-anchors-y-limites

Anchors and Bounds in Regex

  • 3 min

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:

SymbolDescription
^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 ^:

Hola, ¿como estas?

Pero este Hola no lo va a encontrar

While if we want to find strings that end with “adiós”, we use $:

Hasta luego, no va a encontrar este adios, pero si este adios

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:

SymbolDescription
\bRepresents a word boundary
\BRepresents 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:

Mi casa es grande y casadera

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:

La casa esta cerca peor la mia mas

In this case,

  • It finds the match for “as” inside “casa”
  • But it does not find the “as” at the end of “mas”