TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# RegexOptions.Multiline

This C# program uses Regex.Matches and 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.

Plus

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.

Foreach

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, "^(.+)$",
	    RegexOptions.Multiline);
	foreach (Match match in matches)
	{
	    // Loop through captures.
	    foreach (Capture capture in match.Captures)
	    {
		// Display them.
		Console.WriteLine("--" + capture.Value);
	    }
	}
    }
}

Output

--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.

RegexOptions.CompiledRegexOptions.IgnoreCase

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.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf