Combination of C Regular Matching RegexOptions Options

  • 2021-09-16 07:50:45
  • OfStack

The namespaces that need to be referenced to use regularity in C # are using System. Text. RegularExpressions

It consists of eight classes, the most commonly used being Regex, Regex not only can be used to create regular expressions, but also provides many useful methods.

First, let's look at how to create an Regex object under 1:

new Regex(string pattern)

new Regex(string pattern,RegexOptions options)

The first parameter is the regular expression string, and the second parameter is the option of regular configuration, which has the following options:

IgnoreCase//is case sensitive by default for matching ignoring case
RightToLeft//Right-to-left lookup string defaults to left-to-right
None//Do not set flags This is the default option, that is, do not set the second parameter to indicate case sensitivity from left to right
MultiLine//specifies that ^ and $can match the beginning and end of a line, which means that line break is used to get a different match for every 1 line
SingleLine//specifies that the special character "." matches any 1 character except the newline character. By default, the special character '.' does not match the newline

Examples of IgnoreCase


string test = "Abcccccc";
Regex reg = new Regex("abc");
Console.WriteLine(reg.IsMatch(test)); //false
Regex reg1 = new Regex("abc",RegexOptions.IgnoreCase); // Case insensitive 
Console.WriteLine(reg1.IsMatch(test));//true

Examples of RightToLeft


string test = "vvv123===456vvv";
Regex reg = new Regex("\\d+");// 123   From left to right   Matching continuous digits 
Console.WriteLine(reg.Match(test));
Regex reg1 = new Regex("\\d+",RegexOptions.RightToLeft);
Console.WriteLine(reg1.Match(test));// 456  From right to left   Matching continuous digits 

Examples of MultiLine


StringBuilder input = new StringBuilder();
input.AppendLine("A bbbb A");
input.AppendLine("C bbbb C");

string pattern = @"^\w";
Console.WriteLine(input.ToString());
MatchCollection matchCol = Regex.Matches(input.ToString(), pattern, RegexOptions.Multiline);
foreach (Match item in matchCol)
{
  Console.WriteLine(" Results: {0}", item.Value);
}

At this time, some people may ask, what should I do if I want to ignore case and match multiple lines? That is, if both options are satisfied at the same time, what should I do?

Hehe, of course, there are methods, just use vertical lines to separate the two options, as follows


Regex.Matches(input.ToString(), pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);


Related articles: