Language: EN

regex-anchors-y-limites

Anchors and Bounds in Regex

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:

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

Hello, how are you?

But this Hello won't be found

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

See you later, this goodbye won't be found, but this goodbye will

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:

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

My house is big and houseable

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:

The house is nearby but i'm more than you

In this case,

  • It finds the match for “ou” within “house”
  • But does not find the “ou” at the end of “you”