正则表达式:用来匹配某种格式的字符串的模式。
C#中正则表达式需要命名空间system.Text.RegularExpression;
符号 | 含义 | 举例 |
---|---|---|
. | 任意字符 | |
[] | 与括号内的任意字符匹配 | [Bbw]ill 可匹配Bill或bill或will |
[^] | 与括号内之外的任意字符匹配 | [^Bbw]ill 不可匹配Bill或bill或will |
^ | 首,从前往后匹配 | |
$ | 尾,从后往前匹配 | |
() | 分组 | (good|bad)day 可匹配goodday或badday |
| | 或 | |
\ | 转义 | a\(b\)可匹配a(b),反斜杠说明圆括号在此处不是作为一个组的分割符 |
* | 0个或多个 | ^.*$ 可匹配一整行 |
+ | 1个或多个 | a+b可匹配 a后一个或多个字符最后以b结尾 |
? | 0个或1个 | |
^n | 重复 |
用法:
[0-9]可用\d代替
[^ 0-9]可用\D代替 表示非数字
[a-zA-Z]可用\w代替
\s空白
\S非空白
{2,6} 2到6次
*?+??? lazy匹配
C#使用正则表达式的方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions; //正则表达式命名空间
namespace 例1
{
class Program
{
static void Main(string[] args)
{
string s = "my friend Bill will play the bill";
string pattern="[Bbw]ill";
if(Regex.IsMatch(s, pattern)) //用Regex.IsMatch判断是否匹配
Console.WriteLine(s+"与"+pattern+"相匹配");
else
Console.WriteLine("无匹配项");
Regex rx = new Regex(pattern);
MatchCollection mc = rx.Matches(s); //用Matches
Console.WriteLine("有{0}次匹配",mc.Count);
foreach (Match m0 in mc) //foreach循环用Matches
{
Console.WriteLine("在位置{0}处有匹配{1}", m0.Index, m0.Value);
}
for (Match m1 = rx.Match(s); m1.Success; m1 = m1.NextMatch()) //for循环用Match
{
Console.WriteLine(m1);
}
}
}
}