<!doctypehtml><style>svg{width:20px;height:20px;margin:8px auto}body>svg{width:80px;height:60px;margin-top:4px}body>svg,.z>svg,.Z>svg{border-radius:5px}*{margin:0;font-style:normal}.h b,.t>div b{padding-right:10px}html{min-height:110vh}body,a,.V,.h,.Z,.s>div,.t>div{display:grid}html{background:var(--b);--b:#fffbf7;--t:#141414;--e:#efedea;--i:#7a328c;--s:#d9f9ff;--l:#bfbfbf}body{grid:auto/80px auto 48%;gap:25px 20px;max-width:920px;margin:0 auto;padding:0 20px 10px;color:var(--t)}.z,.Z{grid:auto/auto min-content;gap:10px}.z>svg{width:170px;margin:8px 0 0 auto}.z>svg+svg{margin:0 0 14px;width:137px;height:70px}.z>svg+svg,.h{border-radius:0 0 5px 5px}.Z>svg{margin:10px 0;width:125px}.z>svg,.Z>svg{height:64px}.Z a{display:inline}.Z>svg{height:32px;margin-top:0}.O{width:30%;margin:8px 0;border-bottom:2px solid var(--l)}.z>div{letter-spacing:3px;margin:6px 0 0 auto}body,.s>div{font-family:arial,sans-serif}.t,.h,.v,.s>div,.Z>div{line-height:1.6}.h{background:var(--e);padding-right:15px}.s{white-space:pre-wrap;font-family:monospace}a{text-decoration:none;color:inherit}img{object-fit:contain;object-position:0 0;height:45px;width:80px}a,.s>div{font-weight:700}.b>img{width:100%;height:200px}a,.h,.s>div,.t>div{grid:auto/30px auto}.b,.O,img{display:block!important}.v div,.Z,.h,.t>a,.s>div,.t>div{font-size:14px}.h>div,.t>a>div,.t>div>div,a>div{padding:8px 0}.s>div>svg{margin:0 auto}.s>div>div{padding:0 0 8px}.V{grid:45px/repeat(auto-fill,80px);gap:4px}.z:hover>svg{filter:grayscale(1)}a:hover{text-decoration:underline}@media(max-width:699px){body{grid:auto/80px auto;padding:0 10px 10px;gap:10px}.Z,.z,.s,.A,.V,body>span{grid-column-start:span 2}.A,.s{overflow-x:scroll}}@media(min-width:1050px){body{grid:auto/80px auto 51%;gap:25px 20px;max-width:1000px;box-shadow:0 0 20px var(--l);margin:30px auto;border-radius:5px;border:1px solid var(--t)}}@media(min-width:1200px){body{grid:auto/80px auto 54%;max-width:1100px}}@media(prefers-color-scheme:dark){html{--b:#333;--t:#f7f7f7;--e:#424242;--i:#9ee4ff;--s:#413984;--l:#727272}img,.J>svg,.h>svg,.t svg{filter:invert(1)}}.s>span{background:var(--s)}i{color:var(--i)}em{background:var(--e)}</style><link href=https://www.dotnetperls.com/regex rel=canonical><link href=a.svg rel=icon><title>
   C# Regex.Match Examples: Regular Expressions - Dot Net Perls
  </title><meta content=width=device-width,initial-scale=1 name=viewport><meta content="Use the Regex class and Regex.Match, reviewing features from System.Text.RegularExpressions."name=description><body><div class=v><a href=.> <svg><use href=a.svg#favicon></use></svg> <div>Home</div> </a><a class=J href=s> <svg><use href=a.svg#search></use></svg> <div>Search</div> </a></div><div class=h><svg><use href=a.svg#site></use></svg><div><b> C# Regex.Match Examples: Regular Expressions </b> Use the Regex class and Regex.Match, reviewing features from System.Text.RegularExpressions.</div></div><a title="Dot Net Perls"class=z href=.> <svg><use href=a.svg#x></use></svg> <svg><use href=a.svg#h></use></svg> </a><svg><use href=a.svg#c12></use></svg><div class=t><b> Regex. </b> Programs read in text and often must process it in some way. Often the easiest way to process text is with regular expressions. The Regex class in C# helps here.</div><div class=V><img src=regex-match-digit-chart.svg><img src=regex-match-chart.svg><img src=regex-start-end-chart.svg><img src=nextmatch.svg><img src=regex-replace-chart.svg><img src=greedy-regex-chart.svg></div><svg><use href=a.svg#c38></use></svg><div class=t><b> Regex details. </b> With methods like Regex.Match, we pass in a pattern, and receive matches based on that pattern. We can optionally create a Regex instance first.</div><div class=A><script async src=https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js></script><ins class=adsbygoogle data-ad-client=ca-pub-4712093147740724 data-ad-format=auto data-ad-slot=9062372771 data-full-width-responsive=true style=display:block> </ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></div><svg><use href=a.svg#c2></use></svg><div class=t><b> Simple example. </b> This program introduces the Regex class. Regex, and Match, are found in the System.Text.RegularExpressions namespace. <div><svg><use href=a.svg#inset></use></svg><div><b> Step 1 </b> We create a Regex. The Regex uses a pattern that indicates one or more digits.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Step 2 </b> Here we invoke the Match method on the Regex. The characters "55" match the pattern specified in step 1.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Step 3 </b> The returned Match object has a bool property called Success. If it equals true, we found a match.</div></div><div class=b><img src=regex-match-digit-chart.svg></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses Match, Regex</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { <i> // Step 1: create new Regex. </i><b> Regex </b> regex = new Regex( <em> @"\d+" </em> ); <i> // Step 2: call Match on Regex instance. </i> Match match = regex. <b> Match </b> ( <em> "a55a" </em> ); <i> // Step 3: test for Success. </i> if (match. <span> Success </span> ) { Console.WriteLine( <em> "MATCH VALUE: " </em> + match.Value); } } } <div class=O></div> MATCH VALUE: 55</div><svg><use href=a.svg#c11></use></svg><div class=t><b> Complex example. </b> We do not need to create a Regex instance to use Match: we can invoke the static Regex.Match. This example builds up some complexity—we access Groups after testing Success. <div><svg><use href=a.svg#inset></use></svg><div><b> Part 1 </b> This is the string we are testing. Notice how it has a file name part inside a directory name and extension.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Part 2 </b> We use the Regex.Match static method. The second argument is the pattern we wish to match with.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Part 3 </b> We test the result of Match with the Success property. When true, a Match occurred and we can access its Value or Groups.</div></div><a href=regex-groups> <svg><use href=a.svg#arrow></use></svg> <div>Regex Groups</div> </a><div><svg><use href=a.svg#inset></use></svg><div><b> Part 4 </b> We access Groups when Success is true. This collection is indexed at 1, not zero—the first group is found at index 1.</div></div><div class=b><img src=regex-match-chart.svg></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses Regex.Match</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { <i> // Part 1: the input string. </i> string input = <em> "/content/alternate-1.aspx" </em> ; <i> // Part 2: call Regex.Match. </i> Match match = <b> Regex.Match </b> (input, <em> @"content/([A-Za-z0-9\-]+)\.aspx$" </em> , RegexOptions.IgnoreCase); <i> // Part 3: check the Match for Success. </i> if (match. <span> Success </span> ) { <i> // Part 4: get the Group value and display it. </i> string key = match. <b> Groups </b> [1].Value; Console.WriteLine(key); } } } <div class=O></div><em> alternate-1 </em><div class=O></div> @" This starts a verbatim string literal. content/ The group must follow this string. [A-Za-z0-9\-]+ One or more alphanumeric characters. (...) A separate group. \.aspx This must come after the group. $ Matches the end of the string.</div><svg><use href=a.svg#c28></use></svg><div class=t><b> Start, end matching. </b> We can use metacharacters to match the start and end of strings. This is often done when using regular expressions. Use "^" to match the start, and "$" for the end. <div><svg><use href=a.svg#inset></use></svg><div><b> IsMatch </b> Instead of returning a Match object like Regex.Match, IsMatch just returns bool that indicates success.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Also </b> We can use the special start and end-matching characters in Regex.Match—it will return any possible matches at those positions.</div></div><div class=b><img src=regex-start-end-chart.svg></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses IsMatch, start and end</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { string test = <em> "xxyy" </em> ; <i> // Match the start of a string. </i> if (Regex. <b> IsMatch </b> (test, <em> "^xx" </em> )) { Console.WriteLine( <em> "START MATCHES" </em> ); } <i> // Match the end of a string. </i> if (Regex. <b> IsMatch </b> (test, <em> "yy$" </em> )) { Console.WriteLine( <em> "END MATCHES" </em> ); } } } <div class=O></div> START MATCHES END MATCHES <div class=O></div> ^ Match start of string. xx Match 2 x chars. yy Match 2 y chars. $ Match end of string.</div><svg><use href=a.svg#c6></use></svg><div class=t><b> NextMatch. </b> More than one match may be found. We can call NextMatch() to search for a match that comes after the current one in the text. NextMatch can be used in a loop. <div><svg><use href=a.svg#inset></use></svg><div><b> Step 1 </b> We call Regex.Match. Two matches occur. This call to Regex.Match returns the first Match only.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Step 2 </b> NextMatch returns another Match object—it does not modify the current one. We assign a variable to it.</div></div><div class=b><img src=nextmatch.svg></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses NextMatch</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { string value = " <em> 4 AND 5 </em> "; <i> // Step 1: get first match. </i> Match match = <b> Regex.Match </b> (value, <em> @"\d" </em> ); if (match. <span> Success </span> ) { Console.WriteLine(match.Value); } <i> // Step 2: get second match. </i> match = match. <b> NextMatch </b> (); if (match. <span> Success </span> ) { Console.WriteLine(match.Value); } } } <div class=O></div> 4 5</div><svg><use href=a.svg#c0></use></svg><div class=t><b> Replace. </b> Sometimes we need to replace a pattern of text with some other text. Regex.Replace helps. We can replace patterns with a string, or with a value determined by a MatchEvaluator. <a href=regex-replace> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Replace</div> </a><a href=regex-replace-end> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Replace String End</div> </a><a href=regex-replace-numbers> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Replace Numbers</div> </a><a href=regex-replace-spaces> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Replace Spaces</div> </a><a href=regex-trim> <svg><use href=a.svg#arrow></use></svg> <div>Regex Trim</div> </a><div><svg><use href=a.svg#inset></use></svg><div><b> Example </b> We replace all 2 or more digit matches with a string. The 2 digit sequences are replaced with "bird."</div></div><div class=b><img src=regex-replace-chart.svg></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses Replace, replaces with pattern</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { <i> // Replace 2 or more digit pattern with a string. </i> Regex regex = new <b> Regex </b> ( <em> @"\d+" </em> ); string result = regex. <b> Replace </b> ( <em> "cat 123 456" </em> , <em> "bird" </em> ); Console.WriteLine( <em> "RESULT: {0}" </em> , result); } } <div class=O></div> RESULT: cat bird bird <div class=O></div> \d+ One or more digit characters.</div><svg><use href=a.svg#c33></use></svg><div class=t><b> Greedy matching. </b> Some regular expressions want to match as many characters as they can—this is the default behavior. But with the "?" metacharacter, we can change this. <div><svg><use href=a.svg#inset></use></svg><div><b> Version 1 </b> Use the lazy "?" character to match as few characters before the slash as possible.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Version 2 </b> Use the default greedy regular expression behavior—the result Value is as long as possible.</div></div><div class=b><img src=greedy-regex-chart.svg></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses non-greedy Regex</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { string test = <em> "/bird/cat/" </em> ; <i> // Version 1: use lazy (or non-greedy) metacharacter. </i> var result1 = <b> Regex.Match </b> (test, <em> "^/.*?/" </em> ); if (result1.Success) { Console.WriteLine( <em> "NON-GREEDY: {0}" </em> , result1.Value); } <i> // Version 2: default Regex. </i> var result2 = <b> Regex.Match </b> (test, <em> "^/.*/" </em> ); if (result2.Success) { Console.WriteLine( <em> "GREEDY: {0}" </em> , result2.Value); } } } <div class=O></div> NON-GREEDY: /bird/ GREEDY: /bird/cat/ <div class=O></div> ^ Match start of line. / Match forward slash character. .* Zero or more characters, as many as possible. .*? Zero or more characters, as few as possible.</div><svg><use href=a.svg#c16></use></svg><div class=t><b> Static. </b> Often a Regex instance object is faster than the static Regex.Match. For performance, we should usually use an instance object. It can be shared throughout an entire project. <a href=static-regex> <svg><use href=a.svg#arrow></use></svg> <div>Static Regex</div> </a><div><svg><use href=a.svg#inset></use></svg><div><b> Sometimes </b> We only need to call Match once in a program's execution. A Regex object does not help here.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Class </b> Here a static class stores an instance Regex that can be used project-wide. We initialize it inline.</div></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses static Regex</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { <i> // The input string again. </i> string input = <em> "/content/alternate-1.aspx" </em> ; <i> // This calls the static method specified. </i> Console.WriteLine(RegexUtil.MatchKey(input)); } } <span> static </span> class RegexUtil { <span> static </span> Regex _regex = new Regex( <em> @"/content/([a-z0-9\-]+)\.aspx$" </em> ); <i> /// &LTsummary> /// This returns the key that is matched within the input. /// &LT/summary> </i> static public string MatchKey(string input) { Match match = _regex. <b> Match </b> (input.ToLower()); if (match.Success) { return match.Groups[1].Value; } else { return null; } } } <div class=O></div> alternate-1</div><svg><use href=a.svg#c7></use></svg><div class=t><b> Match, parse numbers. </b> A common requirement is extracting a number from a string. We can do this with Regex.Match. To get further numbers, consider Matches() or NextMatch. <div><svg><use href=a.svg#inset></use></svg><div><b> Digits </b> We extract a group of digit characters and access the Value string representation of that number.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Parse </b> To parse the number, use int.Parse or int.TryParse on the Value here. This will convert it to an int.</div></div><a href=parse> <svg><use href=a.svg#arrow></use></svg> <div>int.Parse</div> </a></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that matches and parses a number</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = <em> "Dot Net 100 Perls" </em> ; Match match = <b> Regex.Match </b> (input, <em> @"\d+" </em> ); if (match. <b> Success </b> ) { int. <b> TryParse </b> (match.Value, out int number); <i> // Show that we have the numbers. </i> Console.WriteLine( <em> "NUMBERS: {0}, {1}" </em> , number, number + 1); } } } <div class=O></div> NUMBERS: 100, 101</div><svg><use href=a.svg#c16></use></svg><div class=t><b> Value, length, index. </b> A Match object, returned by Regex.Match has a Value, Length and Index. These describe the matched text (a substring of the input). <div><svg><use href=a.svg#inset></use></svg><div><b> Value </b> This is the matched text, represented as a separate string. This is a substring of the original input.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Length </b> This is the length of the Value string. Here, the Length of "Axxxxy" is 6.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Index </b> The index where the matched text begins within the input string. The character "A" starts at index 4 here.</div></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that shows value, length, index</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { Match m = <span> Regex.Match </span> ("123 <em> Axxxxy </em> ", @"A.*y"); if (m.Success) { Console.WriteLine("Value = " + m. <b> Value </b> ); Console.WriteLine("Length = " + m. <b> Length </b> ); Console.WriteLine("Index = " + m. <b> Index </b> ); } } } <div class=O></div> Value = Axxxxy Length = 6 Index = 4</div><svg><use href=a.svg#c29></use></svg><div class=t><b> IsMatch. </b> This method tests for a matching pattern. It does not capture groups from this pattern. It just sees if the pattern exists in a valid form in the input string. <div><svg><use href=a.svg#inset></use></svg><div><b> Bool </b> IsMatch returns a bool value. Both overloads receive an input string that is searched for matches.</div></div><a href=bool-return> <svg><use href=a.svg#arrow></use></svg> <div>Bool Method</div> </a><div><svg><use href=a.svg#inset></use></svg><div><b> Internals </b> When we use the static Regex.IsMatch method, a new Regex is created. This is done in the same way as any instance Regex.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> And </b> This instance is discarded at the end of the method. It will be cleaned up by the garbage collector.</div></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses Regex.IsMatch method</div></div> using System; using System.Text.RegularExpressions; class Program { <i> /// &LTsummary> /// Test string using Regex.IsMatch static method. /// &LT/summary> </i> static bool IsValid(string value) { return <b> Regex.IsMatch </b> (value, <em> @"^[a-zA-Z0-9]*$" </em> ); } static void Main() { <i> // Test the strings with the IsValid method. </i> Console.WriteLine(IsValid( <em> "dotnetperls0123" </em> )); Console.WriteLine(IsValid( <em> "DotNetPerls" </em> )); Console.WriteLine(IsValid( <em> ":-)" </em> )); <i> // Console.WriteLine(IsValid(null)); // Throws an exception </i> } } <div class=O></div> True True False</div><svg><use href=a.svg#c19></use></svg><div class=t><b> RegexOptions. </b> With the Regex type, the RegexOptions enum is used to modify method behavior. Often I find the IgnoreCase value helpful. <div><svg><use href=a.svg#inset></use></svg><div><b> IgnoreCase </b> Lowercase and uppercase letters are distinct in the Regex text language. IgnoreCase changes this.</div></div><a href=regexoptions-ignorecase> <svg><use href=a.svg#arrow></use></svg> <div>RegexOptions.IgnoreCase</div> </a><div><svg><use href=a.svg#inset></use></svg><div><b> Multiline </b> We can change how the Regex type acts upon newlines with the RegexOptions enum. This is often useful.</div></div><a href=regexoptions-multiline> <svg><use href=a.svg#arrow></use></svg> <div>RegexOptions.Multiline</div> </a></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that uses RegexOptions.IgnoreCase</div></div> using System; using System.Text.RegularExpressions; class Program { static void Main() { const string value = <em> "TEST" </em> ; <i> // ... This ignores the case of the "TE" characters. </i> if (Regex.IsMatch(value, <em> "te.." </em> , <b> RegexOptions.IgnoreCase </b> )) { Console.WriteLine(true); } } } <div class=O></div> True</div><svg><use href=a.svg#c42></use></svg><div class=t><b> Benchmark, Regex. </b> Consider the performance of Regex.Match. If we use the RegexOptions.Compiled enum, and use a cached Regex object, we can get a performance boost. <a href=regexoptions-compiled> <svg><use href=a.svg#arrow></use></svg> <div>RegexOptions.Compiled</div> </a><div><svg><use href=a.svg#inset></use></svg><div><b> Version 1 </b> In this version of the code, we call the static Regex.Match method, without any object caching.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Version 2 </b> Here we access a cached object and call Match() on this instance of the Regex.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Result </b> By using a static field Regex, and RegexOptions.Compiled, our method completes twice as fast (tested on .NET 5 for Linux).</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Warning </b> A compiled Regex will cause a program to start up slower, and may use more memory—so only compile hot Regexes.</div></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that benchmarks Match, RegexOptions.Compiled</div></div> using System; using System.Diagnostics; using System.Text.RegularExpressions; class Program { static int <span> Version1 </span> () { string value = <em> "This is a simple 5string5 for Regex." </em> ; return <b> Regex.Match </b> (value, <em> @"5\w+5" </em> ).Length; } static Regex _wordRegex = new Regex( <em> @"5\w+5" </em> , RegexOptions.Compiled); static int <span> Version2 </span> () { string value = <em> "This is a simple 5string5 for Regex." </em> ; return _wordRegex. <b> Match </b> (value).Length; } const int _max = 1000000; static void Main() { <i> // Version 1: use Regex.Match. </i> var s1 = Stopwatch.StartNew(); <b> for </b> (int i = 0; i < _max; i++) { if ( <span> Version1 </span> () != 8) { return; } } s1.Stop(); <i> // Version 2: use Regex.Match, compiled Regex, instance Regex. </i> var s2 = Stopwatch.StartNew(); <b> for </b> (int i = 0; i < _max; i++) { if ( <span> Version2 </span> () != 8) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString( <em> "0.00 ns" </em> )); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString( <em> "0.00 ns" </em> )); } } <div class=O></div><span> 265.90 ns </span> Regex.Match <span> 138.78 ns </span> instanceRegex.Match, Compiled</div><svg><use href=a.svg#c36></use></svg><div class=t><b> Benchmark, Regex and loop. </b> Regular expressions can be reimplemented with loops. For example, a loop can make sure that a string only contains a certain range of characters. <div><svg><use href=a.svg#inset></use></svg><div><b> Info </b> The string must only contain the characters "a" through "z" lowercase and uppercase, and the ten digits "0" through "9."</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Version 1 </b> This method uses Regex.IsMatch to tell whether the string only has the range of characters specified.</div></div><div><svg><use href=a.svg#inset></use></svg><div><b> Version 2 </b> This uses a for-loop to iterate through the character indexes in the string. It employs a switch on the char.</div></div><a href=for> <svg><use href=a.svg#arrow></use></svg> <div>For</div> </a><a href=switch> <svg><use href=a.svg#arrow></use></svg> <div>Switch</div> </a><div><svg><use href=a.svg#inset></use></svg><div><b> Result </b> In .NET 5 for Linux (tested in 2021) the regular expression is slower than the loop. But Regex performance has been improved.</div></div></div><div class=s><div><svg><use href=a.svg#page></use></svg><div>C# program that benchmarks Regex versus loop</div></div> using System; using System.Diagnostics; using System.Text.RegularExpressions; class Program { static bool <span> IsValid1 </span> (string path) { return Regex.IsMatch(path, <em> @"^[a-zA-Z0-9]*$" </em> ); } static bool <span> IsValid2 </span> (string path) { for (int i = 0; i < path.Length; i++) { switch (path[i]) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { continue; } default: { return false; } } } return true; } const int _max = 1000000; static void Main() { <i> // Version 1: use Regex. </i> var s1 = Stopwatch.StartNew(); <b> for </b> (int i = 0; i < _max; i++) { if (IsValid1( <em> "hello" </em> ) == false || IsValid1( <em> "$bye" </em> ) == true) { return; } } s1.Stop(); <i> // Version 2: use for-loop. </i> var s2 = Stopwatch.StartNew(); <b> for </b> (int i = 0; i < _max; i++) { if (IsValid2( <em> "hello" </em> ) == false || IsValid2( <em> "$bye" </em> ) == true) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString( <em> "0.00 ns" </em> )); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString( <em> "0.00 ns" </em> )); } } <div class=O></div><span> 265.71 ns </span> Regex.IsMatch <span> 10.15 ns </span> for, switch</div><svg><use href=a.svg#c6></use></svg><div class=t><b> Matches. </b> Sometimes one match is not enough. Here we use Matches instead of Match: it returns multiple Match objects at once. These are returned in a MatchCollection. <a href=regex-matches> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Matches</div> </a><a href=regex-matches-quote> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Matches, Quote</div> </a></div><div class=A><ins class=adsbygoogle data-ad-client=ca-pub-4712093147740724 data-ad-format=auto data-ad-slot=9062372771 data-full-width-responsive=true style=display:block> </ins><script>(adsbygoogle=window.adsbygoogle||[]).push({});</script></div><svg><use href=a.svg#c32></use></svg><div class=t><b> Regex.Split. </b> Do you need to extract substrings that contain only certain characters (certain digits, letters)? Split() returns a string array that will contain the matching substrings. <a href=regex-split> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Split</div> </a><a href=regex-split-numbers> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Split Numbers</div> </a></div><span> </span><svg><use href=a.svg#c25></use></svg><div class=t><b> Escape. </b> This method can change a user input to a valid Regex pattern. It assumes no metacharacters were intended. The input string should be only literal characters. <a href=regex-escape> <svg><use href=a.svg#arrow></use></svg> <div>Regex.Escape</div> </a></div><span> </span><svg><use href=a.svg#c16></use></svg><div class=t><b> Word count. </b> With Regex we can count words in strings. We compare this method with Microsoft Word's implementation. We come close to Word's algorithm. <a href=word-count> <svg><use href=a.svg#arrow></use></svg> <div>Word Count</div> </a></div><span> </span><svg><use href=a.svg#c42></use></svg><div class=t><b> Files. </b> We often need to process text files. The Regex type, and its methods, are used for this. But we need to combine a file input type (like StreamReader) with the Regex code. <a href=regex-file> <svg><use href=a.svg#arrow></use></svg> <div>Regex File</div> </a></div><span> </span><svg><use href=a.svg#c25></use></svg><div class=t><b> HTML. </b> Regex can be used to process or extract parts of HTML strings. There are problems with this approach. But it works in many situations. <a href=title-html> <svg><use href=a.svg#arrow></use></svg> <div>Title From HTML</div> </a><a href=paragraph-html> <svg><use href=a.svg#arrow></use></svg> <div>Paragraph HTML Regex</div> </a><a href=remove-html-tags> <svg><use href=a.svg#arrow></use></svg> <div>Remove HTML Tags</div> </a></div><span> </span><svg><use href=a.svg#c37></use></svg><div class=t><b> Review, performance. </b> Regex calls are usually slower than well-written, equivalent char-testing for-loops. We speed things up with RegexOptions.Compiled and cached Regex fields.</div><span> </span><svg><use href=a.svg#c36></use></svg><div class=t><b> A summary. </b> Regular expressions are a concise way to process text data. We use Regex.Matches, and IsMatch, to check a pattern (evaluating its metacharacters) against an input string.</div><span> </span><div class=v><a href=.> <svg><use href=a.svg#favicon></use></svg> <div>Home</div> </a></div><span> </span><div class=Z><div>© 2007-2021 sam allen. see site info on the <a href=changelog> changelog </a></div><svg><use href=a.svg#f></use></svg></div>