C#中的正则表达式和示例

正则表达式是可以与输入文本匹配的模式。.Net框架提供了允许此类匹配的正则表达式引擎。

让我们看看如何分割正则表达式。

要使用正则表达式拆分字符串,请使用Regex.split。

假设我们的字符串是-

string str = "Hello\r\nWorld";

现在使用Regex.split分割字符串,如下所示-

string[] res = Regex.Split(str, "\r\n");

以下是在C#中使用正则表达式拆分字符串的完整代码-

示例

using System;
using System.Text.RegularExpressions;

class Demo {
   static void Main() {
      string str = "Hello\r\nWorld";

      string[] res = Regex.Split(str, "\r\n");

      foreach (string word in res) {
         Console.WriteLine(word);
      }
   }
}

现在让我们看一个删除多余空格的示例。

示例

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();
      }
   }
}