C# RegexOptions.Multiline

RegexOptions.Multiline makes handling multiple lines easier. We apply a regular expression over an input string that has many lines. Each line in the input string should be tested against the entire regular expression.

Example. First, we deal with specific control characters in the regular expression pattern. When specifying a pattern, you can use the "^" character to specify the start of the input string, and the "$" character to specify the end of it.

Plus: The plus sign in the regular expression pattern indicates one or more characters. Zero characters does not match.


In this program, we specify the one or more characters between the start and the end of each line. This matches each line in a capture. We use two foreach-loops to enumerate the results and print them to the screen.

C# program that uses RegexOptions.Multiline

using System;
using System.Text.RegularExpressions;

class Program
    static void Main()
	// Input string.
	const string example = @"This string
has two lines";

	// Get a collection of matches with the Multiline option.
	MatchCollection matches = Regex.Matches(example, "^(.+)$",
	foreach (Match match in matches)
	    // Loop through captures.
	    foreach (Capture capture in match.Captures)
		// Display them.
		Console.WriteLine("--" + capture.Value);


--This string
--has two lines

We see how the RegexOptions.Multiline argument was passed as the third parameter to the Regex.Matches static method. This is how you can use an enumerated constant with the Regex type methods.

Info: There are other RegexOptions you can consider, but they are not covered here.


Summary. RegexOptions.Multiline is useful for treating each separate line in an input string as a separate input. This can make dealing with long input strings much easier, particularly those that contain specially formatted values.