前言
现在复杂的读取文本信息已经离不开正则了,介绍下C#里面正则常用的类。
示例
void regexDemo(string input)
{
//input = aaav0.1.0bbbv0.20.0ccc
//正则表达式
Regex regex = new Regex("v((?<one>[0-9]+?)\\.[0-9]+?\\.[0-9]+?)");
//匹配结果集合
MatchCollection matchs = regex.Matches(input); // matchs.Count = 2
for (int index = 0; index < matchs.Count; index++)
{
Match match = matchs[index];
// index : 0 match : v0.1.0
// index : 1 match : v0.20.0
}
//单个匹配结果
Match SingleMatch = regex.Match(input);
// SingleMatch : v0.1.0
//匹配分组集合
GroupCollection groups = SingleMatch.Groups; // groups.Count = 3
for (var index = 0; index < groups.Count; index++)
{
string groupsValue = groups[index].Value;
// index : 0 value : v0.1.0
// index : 1 value : 0.1.0
// index : 2 value : 0
}
//匹配指定组结果
Group oneGroup = SingleMatch.Groups["one"]; // oneGroup = 0
string value = oneGroup.Value; // value = "0"
}
结构
类
使用正则需要引入System.Text.RegularExpressions,所有相关的类都在这里面。
官网信息:https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions?view=netframework-4.7.2
Regex
Regex是正则表达式,是正则的入口。第一个参数是表达式,第二个参数是正则设置。通常不需要设置第二个参数。
枚举 | 作用 |
---|---|
RegexOptions.None | 未指定任何值 |
RegexOptions.IgnoreCase | 不区分大小写 |
RegexOptions. Multiline | 多行匹配 |
RegexOptions.Singleline | 单行匹配 |
RegexOptions.RightToLeft | 改变匹配顺序,从最右(最后)往最左(最前)匹配 |
RegexOptions.CultureInvariant | 无视语言文化差异,不同的语言环境中同一个字符代表意义不一致 |
RegexOptions.Compiled | 编译成程序集 |
RegexOptions.ECMAScript | 符合ECMAScript行为。只能和IgnorCase,Multiline和Compiled一起使用 |
RegexOptions.ExplicitCapture | 允许捕获组,包括显示 (? <name>)和使用双括号 |
RegexOptions.IgnorePatternWhitespace | 忽视空白区域 |
MatchCollection
MatchCollection是所有的匹配值。包含的是Match的集合。
Match
Match是单个的匹配值结果。无论有多少个匹配结果,都只会返回一个。
里面存储的是具体的匹配结果(Groups)。Match的Groups不会为空,长度一定>=1。当匹配不成功时,值是string.Empty。
索引从0开始,第一个是无关分组的匹配信息。之后是分组的信息。
GroupCollection
GroupCollection是匹配组集合。所有显式命名:(?)和隐式:双括号,都是组。包含的是Group的集合。
需要获取指定组信息时,可以直接使用索引或命名。如:groups[0],groups[“name”]。
Group
Group是匹配组信息。使用value就可以获得到字符串类型的匹配结果。