NET Framework 中的正则表达式引擎由 Regex 类表示。 正则表达式引擎负责分析和编译正则表达式,并执行用于将正则表达式模式与输入字符串相匹配的操作。

Regex 类的方法来执行下列操作:

  • 确定字符串是否与正则表达式模式匹配。

  • 提取单个匹配项或第一个匹配项。

  • 提取所有匹配项。

  • 替换匹配的子字符串。

  • 将单个字符串拆分成一个字符串数组。

以下各部分对这些操作进行了描述。

匹配正则表达式模式

例如,下面的代码将确保字符串与有效的美国社会保障号匹配。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string[] values = { "111-22-3333", "111-2-3333"};
      string pattern = @"^\d{3}-\d{2}-\d{4}$";
      foreach (string value in values) {
         if (Regex.IsMatch(value, pattern))
            Console.WriteLine("{0} is a valid SSN.", value);
         else   
            Console.WriteLine("{0}: Invalid", value);
      }
   }
}
// The example displays the following output:
//       111-22-3333 is a valid SSN.
//       111-2-3333: Invalid

正则表达式模式 ^\d{3}-\d{2}-\d{4}$ 的含义如下表所示。

模式 说明
^ 匹配输入字符串的开头部分。
\d{3} 匹配三个十进制数字。
- 匹配连字符。
$ 匹配输入字符串的末尾部分。

 

 

 

 

提取单个匹配项或第一个匹配项

Match.NextMatch 方法。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is a a farm that that raises dairy cattle."; 
      string pattern = @"\b(\w+)\W+(\1)\b";
      Match match = Regex.Match(input, pattern);
      while (match.Success)
      {
         Console.WriteLine("Duplicate '{0}' found at position {1}.",  
                           match.Groups[1].Value, match.Groups[2].Index);
         match = match.NextMatch();
      }                       
   }
}
// The example displays the following output:
//       Duplicate 'a' found at position 10.
//       Duplicate 'that' found at position 22.

正则表达式模式 \b(\w+)\W+(\1)\b 的含义如下表所示

模式 说明
\b 从单词边界开始进行匹配。
(\w+) 这是第一个捕获组。
\W+ 匹配一个或多个非单词字符。
(\1)

这是第二个捕获组。

\b

在单词边界处结束匹配。

 

 

 

 

 

 

 

替换匹配的子字符串

中的十进制数字前添加美国货币符号。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\d+\.\d{2}\b";
      string replacement = "$$$&"; 
      string input = "Total Cost: 103.64";
      Console.WriteLine(Regex.Replace(input, pattern, replacement));     
   }
}
// The example displays the following output:
//       Total Cost: $103.64

正则表达式模式 \b\d+\. \d{2}\b is interpreted as shown in the following table.

 

模式 说明
\b 在单词边界处开始匹配。
\d+ 匹配一个或多个十进制数字。
\. 匹配句点。
\d{2}

匹配两个十进制数字。

\b

在单词边界处结束匹配。

 

 

 

 

 

 

替换模式 $$$& 的含义如下表所示。

模式 说明
$$ 美元符号 ($) 字符。
$& 整个匹配的子字符串。

 

 

 

 正则语法参考:

https://msdn.microsoft.com/zh-cn/library/az24scfc%28v=vs.110%29.aspx

https://msdn.microsoft.com/zh-cn/library/bs2twtah.aspx

 

 

相关文章: