This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Regular Expressions
.NET 1.1+

Regular Expression Anchors

The fifth part of the Regular Expressions in .NET tutorial continues to look at the characters that make up a regular expression. This article explains how anchors can be used to match patterns based upon their positions within a string or line of text.

Contiguous Match Anchor

The last anchor is the contiguous match anchor (\G). This matches the character position directly following the end of the previous match. The anchor is ideal for extracting items from lists. The first match occurs at the start of the string and any matches that follow immediately are also returned.

To demonstrate try running the following code. Here we are matching numeric characters only and each match must appear directly after the previous one. The first five digits are all matched. The remaining five numbers are not returned because the hyphen stops them from being contiguous matches.

string input = "12345-67890";

foreach (Match match in Regex.Matches(input, @"\G[0-9]"))
    Console.WriteLine("Matched '{0}' at index {1}", match.Value, match.Index);

Matched '1' at index 0
Matched '2' at index 1
Matched '3' at index 2
Matched '4' at index 3
Matched '5' at index 4
19 September 2015