Mega Code Archive

 
Categories / C# Book / 11 Regular Expression Basics
 

0648 Lookahead and Lookbehind

The (?=expr) construct checks whether the text that follows matches expr, without including expr in the result. This is called positive lookahead. In the following example, we look for a number followed by the word "miles": using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.WriteLine (Regex.Match ("25 miles", @"\d+\s(?=miles)")); } } The output: 25 The word "miles" was not returned in the result, even though it was required to satisfy the match. If we append .* to our expression as follows: using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Console.WriteLine (Regex.Match ("25 miles more", @"\d+\s(?=miles).*")); } } The output: 25 miles more