RegexOptions.Multiline. This Regex option makes handling multiple lines easier. With it, we can 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. To restate, a newline means a separate part of the string.
An example. We deal with specific control characters in the regular expression pattern. We can use the "^" char to specify the start of the input string, and "$" to specify the end of it.
Note We specify one or more characters between the start and the end of each line. The plus means "one or more."
Note 2 The pattern matches each line in a capture. We use 2 foreach-loops to enumerate the results and print them to the screen.
Info We see how the RegexOptions.Multiline argument was passed as the third parameter to the Regex.Matches static method.
using System;
using System.Text.RegularExpressions;
// Input string.
const string example = @"This string
has two lines";
// Get a collection of matches with the Multiline option.
MatchCollection matches = Regex.Matches(example, "^(.+)$", RegexOptions.Multiline);
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
Notes, RegexOptions. We can use an enumerated constant with Regex methods. There are other RegexOptions you can consider. For complicate problems, a RegexOptions enum is often needed.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 23, 2023 (edit).