什么是正则表达式?
正则表达式语言是一种专门用于字符串处理的语言。
正则表达式的作用:
1,检索:通过正则表达式,从字符串中获取我们想要的部分
2,匹配:判断给定的字符串是否符合正则表达式的过滤逻辑 你可以认为正则表达式表述了一个字符串的书写规则 判断用户输入的密码是否合法,判断用户输入的邮箱格式是否合法
正则表达式的组成
由普通字符以及特殊字符(成为元字符)组成的文字模式。该模式描述在查找文字主体时待匹配的一个或多个字符串。
正则表达式用来做 检索/匹配 的方法
1.静态方法IsMatch (返回值是一个布尔类型,用于判断指定的字符串是否与正则表达式字符串匹配,它有三个重载方法)
bool isMatch(string input, string pattern); 参数: input:要搜索匹配项的字符串。
pattern:要匹配的正则表达式模式。
返回结果: 如果正则表达式找到匹配项,则为true;否则,为false。
bool IsMatch(string input, string pattern, RegexOptions options); 参数: input:要搜索匹配项的字符串。 pattern:要匹配的正则表达式模式。 options: 枚举值的一个按位组合,这些枚举值提供匹配选项。 返回结果: 如果正则表达式找到匹配项,则为 true;否则,为 false。
bool IsMatch(string input, string pattern, RegexOptions options, TimeSpan matchTimeout); 参数: input:要搜索匹配项的字符串。 pattern:要匹配的正则表达式模式。 options:枚举值的一个按位组合,这些枚举值提供匹配选项。 matchTimeout: 超时间隔,或 System.Text.RegularExpressions.Regex.InfiniteMatchTimeout 指示该方法不 应超时。 返回结果: 如果正则表达式找到匹配项,则为 true;否则,为 false。
2. 静态方法Match,使用指定的匹配选项在输入字符串中搜索指定的正则表达式的第一个匹配项。 返回一个包含有关匹配的信息的对象。同样有三个重载方法,参数和IsMatch方法相同。此外,在Regex类中,还有一个同名的非静态方法,适用于多个实例的情况下,效率更高一些。
Match Match(string input, string pattern); Match Match(string input, string pattern, RegexOptions options); Match Match(string input, string pattern, RegexOptions options, TimeSpan matchTimeout);
3. 静态方法Matches,在指定的输入字符串中搜索指定的正则表达式的所有匹配项。跟上面方法不同之处,就是这个方法返回的是所有匹配项。他同样有三个重载方法,并且参数和Match方法完全相同
MatchCollection Matches(string input, string pattern); MatchCollection Matches(string input, string pattern, RegexOptions options); MatchCollection Matches(string input, string pattern, RegexOptions options, TimeSpan matchTimeout);