主要要素

字符

[a-zA-Z] 即 \w
[0-9] 即 \d
[^0-9] 即 \D
\s 即 空白
\S 即 非空白
. 通配符

次数

* 即 {0,}
+ 即 {1,}
? 即 {0,1}

*? +? ?? 懒惰匹配,尽量匹配少

| 或
() 组合

位置限定

^ 首
$ 尾
\b 单词边界
\B 非单词边界

(?<a>xxxx)(yyyy)

替换时:
${a} => $1 => xxxx
$2 => yyyy

(?i:xxxxx)

忽略大小写

Regex

命名空间:using System.Text.RegularExpressions;

Regex.IsMatch | Match | Matches | Replace(s,r)
Match.Groups | Value | Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Text.RegularExpressions;
class Test
{
static void Main()
{
/*示例*/
string pattern = @"^[\. a-zA-z]+ (?<name>\w+), [a-zA-z]+, x(?<ext>\d+)$";
string [] sa =
{
"Dr. David Jones, Ophthalmology, x2441",
"Ms. Cindy Harriman, Registry, x6231",
"Mr. Chester Addams, Mortuary, x1667",
"Dr. Hawkeye Pierce, Surgery, x0986",
};

Regex rx = new Regex( pattern );

foreach ( string s in sa )
{
Match m= rx.Match(s);
if( m.Success )
Console.Write(m.Result("${ext}, ${name}, $1"));
Console.WriteLine( "\t" +
rx.Replace( s, "姓:${name}, 分机号:${ext}" ));
}

/*示例*/
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);
}
}
}