无涯教程-C# - 正则表达式

85 阅读2分钟

正则表达式是一种可以与输入文本匹配的模式。

Regex类

Regex类用于表示正则表达式。它有以下常用方法-

Sr.No. Methods & 描述
1

public bool IsMatch(string input)

指定的正则表达式是否在指定的input字符串中找到匹配。

2

public bool IsMatch(string input,int startat)

指定的正则表达式是否在指定的input字符串中找到匹配项,从字符串中的指定startat起始位置开始。

3

public static bool IsMatch(string input,string pattern)

指定的正则表达式是否与input字符串找到匹配。

4

public MatchCollection Matches(string input)

指定的字符串中搜索正则表达式的所有匹配项。

5

public string Replace(string input,string replacement)

用指定的替换字符串替换与正则表达式模式匹配的字符串。

6

public string[] split(String Input)

将字符串拆分为子字符串数组。

以下示例匹配以"S"-开头的单词

using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   class Program {
      private static void showMatch(string text, string expr) {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args) {
         string str = "A Thousand Splendid Suns";
         
         Console.WriteLine("Matching words that start with S: ");
         showMatch(str, @"\bS\S*");
         Console.ReadKey();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

Matching words that start with S:
The Expression:\bS\S*
Splendid
Suns

以下示例匹配以‘m开头并以‘e-结尾的单词

using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   class Program {
      private static void showMatch(string text, string expr) {
         Console.WriteLine("The Expression: " + expr);
         MatchCollection mc = Regex.Matches(text, expr);
         
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      static void Main(string[] args) {
         string str = "make maze and manage to measure it";

         Console.WriteLine("Matching words start with m and ends with e:");
         showMatch(str, @"\bm\S*e\b");
         Console.ReadKey();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

Matching words start with m and ends with e:
The Expression:\bm\S*e\b
make
maze
manage
measure

此下示例替换了额外的空白-

using System;
using System.Text.RegularExpressions;

namespace RegExApplication {
   class Program {
      static void Main(string[] args) {
         string input = "Hello   World   ";
         string pattern = "\\s+";
         string replacement = " ";
         
         Regex rgx = new Regex(pattern);
         string result = rgx.Replace(input, replacement);

         Console.WriteLine("Original String: {0}", input);
         Console.WriteLine("Replacement String: {0}", result);    
         Console.ReadKey();
      }
   }
}

编译并执行上述代码时,将生成以下输出-

Original String: Hello World   
Replacement String: Hello World   

参考链接

www.learnfk.com/csharp/csha…