首页 > 代码库 > 正则表达式入门(c#)

正则表达式入门(c#)

本文是对该教程的学习练习

http://www.jb51.net/tools/zhengze.html

 

1.\bContent\b

static void Main(string[] args){    string str = "Act game - Uncharted3, act Game - God of war";    Regex rex = new Regex(@"\bact\b");    var result = rex.Match(str);    if (result.Success)    {        var tmp = result.Index;        Console.WriteLine(tmp);    }    else    {        Console.WriteLine("failure");    }    Console.Read();}
View Code

输出结果:23。

第一个act,a是大写。没做大小写匹配,所以正则匹配到的是索引23的那个act.

 

 

2.\bContent1\b.*\bContent2\b

 

static void Main(string[] args){    string str = "rpg game - Legend of Heroes, act game - Uncharted3, act Game - God of war";    Regex rex = new Regex(@"\bact\b.*\bUncharted3\b");    var result = rex.Match(str);    if (result.Success)    {        var tmp = result.Index;        Console.WriteLine(tmp);    }    else    {        Console.WriteLine("failure");    }    Console.Read();}
View Code

 

输出结果:29。

但是遇到多个和前缀相同的字串,就会出问题。

 

3.0\d\d-\d\d\d\d\d\d\d\d

string str = "the xxxx, xxxx, 021-88888888";Regex rex = new Regex(@"0\d\d-\d\d\d\d\d\d\d\d");...
View Code

输出结果16

算是占位符,匹配电话号码啥的。代码后面都一样就省略掉。

 

4.0\d{2}-\d{8}

 

string str = "the xxxx, xxxx, 021-88888888";Regex rex = new Regex(@"0\d{2}-\d{8}");...
View Code

 

输出结果16

上面那种写法的优化版。