MachCollection
从文本中匹配到符合规则的内容,保存到集合mac中
//正则表达式 匹配()里的内容、
string str = "计算机(CPU)你好(Hello)(Hi) English(英语)";
string reg = @"(?<=[((])[^()()]*(?=[))])";
MatchCollection mac = Regex.Matches(str,reg);
foreach (Match item in mac) {
Console.WriteLine(item.Value);
}
//匹配【】里的地名,
string str = "计算机(CPU)你好【杭州市桐庐县】(Hi) English(英语)【金华市义乌市】【12】[12]";
string reg = @"(?<=【)(([\u4e00-\u9fa5]{2,}市)([\u4e00-\u9fa5]{2,}(县|市|区)))(^【】)*(?=】)";
MatchCollection mac = Regex.Matches(str, reg);
foreach (Match item in mac)
{
Console.WriteLine(item.Value);
}
isMatch
判断文本中是否有符合规则的内容,返回一个bool值
bool b = Regex.IsMatch(str,reg);
Console.WriteLine(b);//True
对它们描述如下:
Regex :正则表达式类,代表了一个不可变的正则表达式。
Match :代表了 Regex 类的实例的一次匹配结果,可以通过 Regex 的 Match() 实例方法返回一个 Match 的实例。
MatchCollection :代表了 Regex 类的实例的所有匹配结果,可以通过 Regex 的 Matches() 实例方法返回一个 MatchCollection 的实例。
Group :表示单个捕获组的结果。由于一次匹配可能包含 0 个、 1 个或多个分组,所以 Match 的实例中返回的是捕获组集合的结果,即 GroupCollection 。
GroupCollection :表示单个匹配中的多个捕获组的集合,可以通过 Match 的 Groups 实例属性返回 GroupCollection 的实例。
Capture :表示单个捕获中的一个子字符串。同 Group 一样,由于一个捕获中可能包含 0 个、 1 个或多个子字符串,所以 Group 的实例中返回的是子字符串集合的结果,即 CaptureCollection 。
CaptureCollection :默认表示按照从里到外、从左到右的顺序由捕获组匹配到的所有子字符串集合,可以通过 Group 或者 Match 的 Captures 实例属性返回CaptureCollection 的实例。注意,可以使用 RegexOptions.RightToLeft 来改变这种匹配顺序。
RegexOptions :提供用于设置正则表达式选项的枚举值。 像上面提到的 RightToLeft 就是它的一个枚举值之一,除此之外还有 None 、 IgnoreCase 、 Multiline 、ExplicitCapture 、 Compiled 、 Singleline 、 IgnorePatternWhitespace 、 RightToLeft 、 ECMAScript 及 CultureInvariant 。 RegexOptions 枚举值可以相加,比如我们想匹配不区分大小写的字符串“ abc ”并且还想提高一下执行速度,那么可以写如下代码:
RegexOptions options=RegexOptions.IgnoreCase|RegexOptions.Compiled;
Regex regex=new Regex(“abc”,options);