C# 正则表达式示例

csharpprogrammingserver side programming更新于 2025/9/2 6:07:17

正则表达式是一种可以与输入文本匹配的模式。.NET 框架提供了一个支持此类匹配的正则表达式引擎。

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

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

假设我们的字符串为 −

string str = "Hello\r
World";

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

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

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

示例

using System;
using System.Text.RegularExpressions;

class Demo {
   static void Main() {
      string str = "Hello\r
World";       string[] res = Regex.Split(str, "\r
");       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();
      }
   }
}

相关文章