控制台正则匹配示例代码,需要引用命名空间:
using System.Text.RegularExpressions;
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace RegularExpressTest
{
class Program
{
static void Main(string[] args)
{
string pattern = "[Bbw]ill"; //要匹配的正则样式
string s = "My friend Bill will pay the bill"; //要匹配的字符串
if (Regex.IsMatch(s, pattern)) //匹配判断
Console.WriteLine(s + "与" + pattern + "相匹配");
Regex rx = new Regex(pattern); //初始化对象
MatchCollection mc = rx.Matches(s);
Console.WriteLine("有{0}次匹配", mc.Count); //获取匹配次数
foreach (Match mt in mc) //获取匹配到的字符串
{
Console.WriteLine(mt);
}
Match m = rx.Match(s); //获取匹配索引及值
while (m.Success)
{
Console.WriteLine("在位置 {0} 有匹配'{1}'",
m.Index, m.Value);
m = rx.Match(s, m.Index + m.Length);
}
for (m = rx.Match(s); m.Success; m = m.NextMatch())
{
Console.WriteLine("在位置 {0} 有匹配'{1}'",
m.Index, m.Value);
}
Console.Read();
}
}
}