C#正则的与众不同

今天在技术问答中看问题时看到有关正则的提问,C#中的正则涉及的还是有很多的。

我们先看看js中的正则:

下面的示例演示了js中match函数方法的用法:

function MatchDemo(){ 
var r, re; // 声明变量。 
var s = "The rain in Spain falls mainly in the plain"; 
re = /ain/i; // 创建正则表达式模式。 
r = s.match(re); // 尝试匹配搜索字符串。 
return(r); // 返回第一次出现 "ain" 的地方。 
}


本示例说明带 g 标志设置的js中match函数方法的用法 
function MatchDemo(){ 
var r, re; // 声明变量。 
var s = "The rain in Spain falls mainly in the plain"; 
re = /ain/ig; // 创建正则表达式模式。 
r = s.match(re); // 尝试去匹配搜索字符串。 
return(r); // 返回的数组包含了所有 "ain" 
// 出现的四个匹配。 
} 

js中的运用很简单,看一下这张思维导图



觉得哪里有欠缺可以去补补。

下面转入正题,C#中的正则;C#的正则涉及到 System.Text.RegularExpressions 命名空间,System.Text.RegularExpressions 命名空间包含提供对.NET Framework 正则表达式引擎的访问的类。

System.Text.RegularExpressions 命名空间:

类:

Capture 表示来自单个成功子表达式捕获的结果。

CaptureCollection 表示单个捕获组执行的捕获集。

Group 表示来自单个捕获组的结果。

GroupCollection  返回一次匹配中捕获的组的集。

Match   表示单个正则表达式匹配的结果。

MatchCollection     表示通过以迭代方式将正则表达式模式应用于输入字符串所找到的成功匹配的集合。

Regex     表示不可变的正则表达式。

RegexCompilationInfo        提供有关用于正则表达式编译为独立的程序集的正则表达式的信息。

RegexMatchTimeoutException     正则表达式模式匹配方法的执行时间超出其超时时间间隔时引发的异常。

RegexRunner         此 API 支持 产品 基础结构,不应从代码直接使用。 RegexRunner 类是已编译的正则表达式类的基类。

RegexRunnerFactory      此 API 支持 产品 基础结构,不应从代码直接使用。 创建 RegexRunner 的已编译的正则表达式类。


委托:

MatchEvaluator     表示期间找到正则表达式匹配每次调用的方法 Replace 方法操作。


枚举:

RegexOptions    提供用于设置正则表达式选项的枚举值。


用一张图来展现各个类之间的关系:



下面来详细了解每一个类:

Capture  类(System.Text.RegularExpressions.Capture):

1、语法

[SerializableAttribute]
public class Capture

2、属性

Index   获取被捕获的第一个子串在原始字符串中的位置。

Length  获取捕获的子字符串的长度。

Value  获取捕获的子字符串。


3、方法

Equals(Object)   确定指定的对象是否等于当前对象。

Finalize()  在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。

GetHashCode()   作为默认哈希函数。

GetType()  获取当前实例的 Type。

MemberwiseClone()   创建当前 Object 的浅表副本。

ToString()   通过调用从输入字符串中检索捕获的子字符串 Value 属性。


4、示例

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "Yes. This dog is very friendly.";
      string pattern = @"((\w+)[\s.])+";
      foreach (Match match in Regex.Matches(input, pattern))
      {
         Console.WriteLine("Match: {0}", match.Value);
         for (int groupCtr = 0; groupCtr < match.Groups.Count; groupCtr++)
         {
            Group group = match.Groups[groupCtr];
            Console.WriteLine("   Group {0}: {1}", groupCtr, group.Value);
            for (int captureCtr = 0; captureCtr < group.Captures.Count; captureCtr++)
               Console.WriteLine("      Capture {0}: {1}", captureCtr, 
                                 group.Captures[captureCtr].Value);
         }                      
      }
   }
}
// 输出:
//       Match: Yes.
//          Group 0: Yes.
//             Capture 0: Yes.
//          Group 1: Yes.
//             Capture 0: Yes.
//          Group 2: Yes
//             Capture 0: Yes
//       Match: This dog is very friendly.
//          Group 0: This dog is very friendly.
//             Capture 0: This dog is very friendly.
//          Group 1: friendly.
//             Capture 0: This
//             Capture 1: dog
//             Capture 2: is
//             Capture 3: very
//             Capture 4: friendly.
//          Group 2: friendly
//             Capture 0: This
//             Capture 1: dog
//             Capture 2: is
//             Capture 3: very
//             Capture 4: friendly

CaptureCollection   类( System.Text.RegularExpressions . CaptureCollection):

1、语法

[SerializableAttribute]
public class CaptureCollection : ICollection, IEnumerable

2、属性

Count  获取组捕获的子字符串的数目。

IsReadOnly  获取一个值,指示集合是否为只读集合。

IsSynchronized   获取一个值,该值指示对集合的访问是否同步(线程安全)。

Item[Int32]   获取该集合的单个成员。

SyncRoot   获取可用于同步对集合的访问的对象。


3、方法

CopyTo(Array, Int32)  将集合的所有元素复制到给定数组中(从给定索引处开始)。

Equals(Object)   确定指定的对象是否等于当前对象。(继承自 Object)

Finalize()   在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object)

GetEnumerator()  提供一个循环访问集合的枚举器。

GetHashCode()   作为默认哈希函数。(继承自 Object)

GetType()   获取当前实例的 Type。(继承自 Object)

MemberwiseClone()  创建当前 Object 的浅表副本。(继承自 Object)

ToString()   返回表示当前对象的字符串。(继承自 Object)


4、扩展方法

AsParallel()   已重载。启用查询的并行化。(由 ParallelEnumerable 定义)

AsQueryable()  已重载。将转换 IEnumerable 到 IQueryable。(由 Queryable 定义)

Cast<TResult>()  将强制转换的元素 IEnumerable 为指定的类型。(由 Enumerable 定义)

OfType<TResult>()  筛选的元素 IEnumerable 根据指定的类型。(由 Enumerable 定义)


5、示例

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern;  
      string input = "The young, hairy, and tall dog slowly walked across the yard.";
      Match match;

      // Match a word with a pattern that has no capturing groups.
      pattern = @"\b\w+\W{1,2}";
      match = Regex.Match(input, pattern);
      Console.WriteLine("Pattern: " + pattern);
      Console.WriteLine("Match: " + match.Value);
      Console.WriteLine("  Match.Captures: {0}", match.Captures.Count);
      for (int ctr = 0; ctr < match.Captures.Count; ctr++)
         Console.WriteLine("    {0}: '{1}'", ctr, match.Captures[ctr].Value);
      Console.WriteLine("  Match.Groups: {0}", match.Groups.Count);
      for (int groupCtr = 0; groupCtr < match.Groups.Count; groupCtr++)
      {
         Console.WriteLine("    Group {0}: '{1}'", 
                           groupCtr, match.Groups[groupCtr].Value);
         Console.WriteLine("    Group({0}).Captures: {1}", 
                           groupCtr, match.Groups[groupCtr].Captures.Count);
         for (int captureCtr = 0; captureCtr < match.Groups[groupCtr].Captures.Count; captureCtr++)
            Console.WriteLine("      Capture {0}: '{1}'", 
                              captureCtr, 
                              match.Groups[groupCtr].Captures[captureCtr].Value);
      }
      Console.WriteLine("-----\n");

      // Match a sentence with a pattern that has a quantifier that 
      // applies to the entire group.
      pattern = @"(\b\w+\W{1,2})+";
      match = Regex.Match(input, pattern);
      Console.WriteLine("Pattern: " + pattern);
      Console.WriteLine("Match: " + match.Value);
      Console.WriteLine("  Match.Captures: {0}", match.Captures.Count);
      for (int ctr = 0; ctr < match.Captures.Count; ctr++)
         Console.WriteLine("    {0}: '{1}'", ctr, match.Captures[ctr].Value);

      Console.WriteLine("  Match.Groups: {0}", match.Groups.Count);
      for (int groupCtr = 0; groupCtr < match.Groups.Count; groupCtr++)
      {
         Console.WriteLine("    Group {0}: '{1}'", groupCtr, match.Groups[groupCtr].Value);
         Console.WriteLine("    Group({0}).Captures: {1}", 
                           groupCtr, match.Groups[groupCtr].Captures.Count);
         for (int captureCtr = 0; captureCtr < match.Groups[groupCtr].Captures.Count; captureCtr++)
            Console.WriteLine("      Capture {0}: '{1}'", captureCtr, match.Groups[groupCtr].Captures[captureCtr].Value);
      }
   }
}
//输出:
//    Pattern: \b\w+\W{1,2}
//    Match: The
//      Match.Captures: 1
//        0: 'The '
//      Match.Groups: 1
//        Group 0: 'The '
//        Group(0).Captures: 1
//          Capture 0: 'The '
//    -----
//    
//    Pattern: (\b\w+\W{1,2})+
//    Match: The young, hairy, and tall dog slowly walked across the yard.
//      Match.Captures: 1
//        0: 'The young, hairy, and tall dog slowly walked across the yard.'
//      Match.Groups: 2
//        Group 0: 'The young, hairy, and tall dog slowly walked across the yard.'
//        Group(0).Captures: 1
//          Capture 0: 'The young, hairy, and tall dog slowly walked across the yard.'
//        Group 1: 'yard.'
//        Group(1).Captures: 11
//          Capture 0: 'The '
//          Capture 1: 'young, '
//          Capture 2: 'hairy, '
//          Capture 3: 'and '
//          Capture 4: 'tall '
//          Capture 5: 'dog '
//          Capture 6: 'slowly '
//          Capture 7: 'walked '
//          Capture 8: 'across '
//          Capture 9: 'the '
//          Capture 10: 'yard.'


Group  类( System.Text.RegularExpressions . Group):

1、语法

[SerializableAttribute]
public class Group : Capture

2、属性

Captures   获取由捕获组,顺序最内层的最左侧第一个匹配的所有捕获的集合 (或如果使用修改正则表达式的最内层的最右边第一个订单 RegexOptions.RightToLeft 选项)。 该集合可以有零个或多个项。

Index  在其中找到被捕获子串的第一个字符的原始字符串中的位置。(继承自 Capture)

Length  获取捕获的子字符串的长度。(继承自 Capture)

Name  返回由当前实例表示的捕获组的名称。

Success     获取一个值,该值指示匹配是否成功。

Value   获取捕获的子字符串的输入字符串中。(继承自 Capture)


3、方法

Equals(Object)   确定指定的对象是否等于当前对象。(继承自 Object)

Finalize()  在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object)

GetHashCode()  作为默认哈希函数。(继承自 Object)

GetType()  获取当前实例的 Type。(继承自 Object)

MemberwiseClone()  创建当前 Object 的浅表副本。(继承自 Object)

Synchronized(Group)   返回 Group 等效于提供的一个对象,该对象,则可以安全多个线程间共享。

ToString()  通过调用从输入字符串中检索捕获的子字符串 Value 属性。(继承自 Capture)


4、示例

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"(\b(\w+?)[,:;]?\s?)+[?.!]";
      string input = "This is one sentence. This is a second sentence.";

      Match match = Regex.Match(input, pattern);
      Console.WriteLine("Match: " + match.Value);
      int groupCtr = 0;
      foreach (Group group in match.Groups)
      {
         groupCtr++;
         Console.WriteLine("   Group {0}: '{1}'", groupCtr, group.Value);
         int captureCtr = 0;
         foreach (Capture capture in group.Captures)
         {
            captureCtr++;
            Console.WriteLine("      Capture {0}: '{1}'", captureCtr, capture.Value);
         }
      }   
   }
}
// 输出:
//       Match: This is one sentence.
//          Group 1: 'This is one sentence.'
//             Capture 1: 'This is one sentence.'
//          Group 2: 'sentence'
//             Capture 1: 'This '
//             Capture 2: 'is '
//             Capture 3: 'one '
//             Capture 4: 'sentence'
//          Group 3: 'sentence'
//             Capture 1: 'This'
//             Capture 2: 'is'
//             Capture 3: 'one'
//             Capture 4: 'sentence'

GroupCollection  类( System.Text.RegularExpressions.GroupCollection):

1、语法

[SerializableAttribute]
public class GroupCollection : ICollection, IEnumerable


2、属性

Count   返回集合中的组数。

IsReadOnly    获取一个值,指示集合是否为只读集合。

IsSynchronized      获取一个值,该值指示是否同步对 GroupCollection 的访问(线程安全)。

Item[Int32]   允许通过整数索引访问集合成员。

Item[String]   允许通过字符串索引访问集合成员。

SyncRoot   获取可用于同步对 GroupCollection 的访问的对象。


3、方法

CopyTo(Array, Int32)   将集合的所有元素复制到给定数组中(从给定索引处开始)。

Equals(Object)   确定指定的对象是否等于当前对象。(继承自 Object。)

Finalize()   在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object。)

GetEnumerator()   提供一个循环访问集合的枚举器。

GetHashCode()  作为默认哈希函数。(继承自 Object。)

GetType()   获取当前实例的 Type。(继承自 Object。)

MemberwiseClone()  创建当前 Object 的浅表副本。(继承自 Object。)

ToString()  返回表示当前对象的字符串。(继承自 Object。)


4、扩展方法

AsParallel()  已重载。启用查询的并行化。(由 ParallelEnumerable 定义。)

AsQueryable()  已重载。将转换 IEnumerable 到 IQueryable。(由 Queryable 定义。)

Cast<TResult>()  将强制转换的元素 IEnumerable 为指定的类型。(由 Enumerable 定义。)

OfType<TResult>()  筛选的元素 IEnumerable 根据指定的类型。(由 Enumerable 定义。)


5、示例

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b(\w+?)([\u00AE\u2122])";
      string input = "Microsoft® Office Professional Edition combines several office " +
                     "productivity products, including Word, Excel®, Access®, Outlook®, " +
                     "PowerPoint®, and several others. Some guidelines for creating " +
                     "corporate documents using these productivity tools are available " +
                     "from the documents created using Silverlight™ on the corporate " +
                     "intranet site.";

      MatchCollection matches = Regex.Matches(input, pattern);
      foreach (Match match in matches)
      {
         GroupCollection groups = match.Groups;
         Console.WriteLine("{0}: {1}", groups[2], groups[1]);
      }                               
      Console.WriteLine();
      Console.WriteLine("Found {0} trademarks or registered trademarks.", matches.Count);
   }
}
// The example displays the following output:
//       r: Microsoft
//       r: Excel
//       r: Access
//       r: Outlook
//       r: PowerPoint
//       T: Silverlight


Match   类(System.Text.RegularExpressions.Match):

1、语法

[SerializableAttribute]
public class Match : Group

2、属性

Captures  获取由捕获组,顺序最内层的最左侧第一个匹配的所有捕获的集合 (或如果使用修改正则表达式的最内层的最右边第一个订单 RegexOptions.RightToLeft 选项)。 该集合可以有零个或多个项。(继承自 Group。)

Empty  获取空组。 所有失败的匹配都返回此空匹配。

Groups  获取由正则表达式匹配的组的集合。

Index  在其中找到被捕获子串的第一个字符的原始字符串中的位置。(继承自 Capture。)

Length  获取捕获的子字符串的长度。(继承自 Capture。)

Name   返回由当前实例表示的捕获组的名称。(继承自 Group。)

Success  获取一个值,该值指示匹配是否成功。(继承自 Group。)

Value  获取捕获的子字符串的输入字符串中。(继承自 Capture。)


3、方法

Equals(Object)   确定指定的对象是否等于当前对象。(继承自 Object。)

Finalize()   在垃圾回收将某一对象回收前允许该对象尝试释放资源并执行其他清理操作。(继承自 Object。)

GetHashCode()   作为默认哈希函数。(继承自 Object。)

GetType()   获取当前实例的 Type。(继承自 Object。)

MemberwiseClone()   创建当前 Object 的浅表副本。(继承自 Object。)

NextMatch()    从上一个匹配结束的位置(即在上一个匹配字符之后的字符)开始返回一个包含下一个匹配结果的新 Match 对象。

Result(String)  返回对指定替换模式的扩展。

Synchronized(Match)    返回一个与提供的实例等效的 Match 实例,该实例适合在多个线程间共享。

ToString()   通过调用从输入字符串中检索捕获的子字符串 Value 属性。(继承自 Capture。)


4、示例

例子一:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "int[] values = { 1, 2, 3 };\n" +
                     "for (int ctr = values.GetLowerBound(1); ctr <= values.GetUpperBound(1); ctr++)\n" +
                     "{\n" +
                     "   Console.Write(values[ctr]);\n" +
                     "   if (ctr < values.GetUpperBound(1))\n" +
                     "      Console.Write(\", \");\n" +
                     "}\n" +
                     "Console.WriteLine();\n";   

      string pattern = @"Console\.Write(Line)?";
      MatchCollection matches = Regex.Matches(input, pattern);
      foreach (Match match in matches)
         Console.WriteLine("'{0}' found in the source code at position {1}.",  
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 115.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 211.


例子二:

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "int[] values = { 1, 2, 3 };\n" +
                     "for (int ctr = values.GetLowerBound(1); ctr <= values.GetUpperBound(1); ctr++)\n" +
                     "{\n" +
                     "   Console.Write(values[ctr]);\n" +
                     "   if (ctr < values.GetUpperBound(1))\n" +
                     "      Console.Write(\", \");\n" +
                     "}\n" +
                     "Console.WriteLine();\n";   
      string pattern = @"Console\.Write(Line)?";
      Match match = Regex.Match(input, pattern);
      while (match.Success)
      {
         Console.WriteLine("'{0}' found in the source code at position {1}.",  
                           match.Value, match.Index);
         match = match.NextMatch();
      }
   }
}
// The example displays the following output:
//    'Console.Write' found in the source code at position 115.
//    'Console.Write' found in the source code at position 184.
//    'Console.WriteLine' found in the source code at position 211.


今天先到这里!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值