Regex Anchors

Summary: in this tutorial, you will learn about regex anchors and how to use them to match the position at the beginning and then end of a line.

Introduction to the regex anchors

Anchors in regular expressions are special characters that define specific positions within the text for matching.

Unlike the character classes, anchors do not match any characters themselves but represent the positions in the text where a match should occur.

Anchors are useful when you want to enforce constraints on where a pattern should match within the input string.

Anchors have two types:

  • Start of line anchor (^): matches the position at the beginning of a line. When you place the caret (^) at the beginning of a regular expression, it ensures the pattern must appear at the start of the line.
  • End of line anchor ($): matches the position at the end of a line. When you place the dollar sign ($) at the end of a regular expression, it ensures the preceding pattern must appear at the end of a line.

Regex anchors examples

The following example uses the \d character class to match two digits in a time string:

using System.Text.RegularExpressions;
using static System.Console;


var time = "11:30";
var pattern = @"\d\d";

var matches = Regex.Matches(time, pattern);
foreach (var match in matches)
{
    WriteLine(match);
}Code language: C# (cs)

Output:

11
30Code language: C# (cs)

It returns two matches because both \d\d pattern matches both 11 and 30.

However, if you use the ^ anchor character at the beginning of the regular expression pattern, it will match only 11 like this:

using System.Text.RegularExpressions;
using static System.Console;


var time = "11:30";
var pattern = @"^\d\d";

var matches = Regex.Matches(time, pattern);
foreach (var match in matches)
{
    WriteLine(match);
}Code language: C# (cs)

Output:

11Code language: C# (cs)

The ^\d\d ensures that the match occurs at the beginning of the input string.

Similarly, when you use the $ anchor at the end of the regular expression pattern, it will match only at the end of the string:

using System.Text.RegularExpressions;
using static System.Console;


var time = "11:30";
var pattern = @"\d\d$";

var matches = Regex.Matches(time, pattern);
foreach (var match in matches)
{
    WriteLine(match);
}Code language: C# (cs)

Output:

30Code language: C# (cs)

Summary

  • Regex anchors match the position, not the characters.
  • The caret anchor (^) matches at the beginning of a line.
  • The dollar anchor ($) matches at the end of a line.
Was this tutorial helpful ?