C#正则表达式 - 精通版

时间:2021-01-14 19:58:26

1、正则所需要的命名空间是

using System.Text.RegularExpressions

2、创建Regex对象

new Regex(string pattern,RegexOptions options)

选项(options)注释
None:指定不设置任何选项
IgnoreCase:指定不区分大小写的匹配 。
Multiline:多行模式。 更改 ^ 和 $ 的含义,使它们分别在任意一行的行首和行尾匹配,而不仅仅在整个字符串的开头和结尾匹配
ExplicitCapture:指定唯一有效的捕获是显式命名或编号的 (?<name>…) 形式的组
Compiled:指定将正则表达式编译为程序集
Singleline:指定单行模式。 更改点 (.) 的含义,以使它与每个字符(而不是除 \n 之外的所有字符)匹配
IgnorePatternWhitespace:消除模式中的非转义空白并启用由 # 标记的注释
RightToLeft:指定搜索从右向左而不是从左向右进行
ECMAScript:为表达式启用符合 ECMAScript 的行为
CultureInvariant:指定忽略语言中的区域性差异

3、匹配
摘要:
指示所指定的正则表达式是否使用指定的匹配选项在指定的输入字符串中找到了匹配项。

语法:

IsMatch(string input, string pattern, RegexOptions options)

参数:
input:
要搜索匹配项的字符串。

pattern:
要匹配的正则表达式模式。

options:
枚举值的一个按位组合,这些枚举值提供匹配选项。

实例:字符串中是否包含数字
方式一,静态方法

bool bl = Regex.IsMatch("AbC123", @"\d+");
Response.Write(bl); 结果:True

方式二,实例方法

Regex reg = new Regex(@"\d+");
bool bl = reg.IsMatch("AbC123");
Response.Write(bl); 结果:True

4、替换

摘要:在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串

语法:

Replace(string input, string pattern, string replacement, RegexOptions options)

参数:
input:
要搜索匹配项的字符串。
pattern:
要匹配的正则表达式模式。
replacement:
替换字符串。
options:
枚举值的一个按位组合,这些枚举值提供匹配选项。如:RegexOptions.IgnoreCase,指定不区分大小写的匹配

实例:字符串中所有字母替换为空(string.Empty)
方式一,静态方法

string str = Regex.Replace("AbC123", "[a-z]", string.Empty, RegexOptions.IgnoreCase);
Response.Write(str); 结果:123

方式二,实例方法

Regex reg = new Regex(@"[a-z]", RegexOptions.IgnoreCase);
string str = reg.Replace("AbC123",string.Empty);
Response.Write(str); 结果:123

5、获取

语法:

Match(string input, string pattern, RegexOptions options)

摘要:
使用指定的匹配选项和超时间隔在输入字符串中搜索指定的正则表达式的第一个匹配项

语法:

Matches(string input, string pattern, RegexOptions options)

摘要:
使用指定的匹配选项和超时间隔在指定的输入字符串中搜索指定的正则表达式的所有匹配项

参数:
input:
要搜索匹配项的字符串。
pattern:
要匹配的正则表达式模式。
options:
枚举值的一个按位组合,这些枚举值提供匹配选项。

方法:
NextMatch 返回下一个成功匹配的match对象
Result
Value 返回匹配的字符串
Length 匹配的长度
Index 第一个匹配内容在字符串中的起始位置
Groups 返回一个分组对象集合
Success 根据是否匹配成功返回ture or false

实例一:提取字符串中所有的数字

Regex reg = new Regex(@"\d+");
Match match = reg.Match("1+2-3");
StringBuilder str = new StringBuilder();
while (match.Success)
{
str.Append(match.Value);
//从匹配结果的位置创建新的Match对象
match = match.NextMatch();
}
Response.Write(str.ToString()); //结果:123

实例二:提取字符串中所有的数字
方式一,静态方法

StringBuilder str = new StringBuilder();
foreach (Match m in Regex.Matches("1+2-3", @"(\d+)"))
{
str.Append(m.Groups[0].Value);
}
Response.Write(str.ToString()); //结果:123 方式二,实例方法
StringBuilder str = new StringBuilder();
Regex reg = new Regex(@"\d+", RegexOptions.IgnoreCase);
MatchCollection matchs = reg.Matches("1+2-3");
foreach (Match item in matchs)
{
str.Append(item.Value);
}
Response.Write(str.ToString()); //结果:123