Regex一些基本的方法

//匹配举例 Regex.IsMatch

while (true)

{

 //电话号码规则:010-11111111,0531-1111111,10086,13800000000

 Console.WriteLine("请输入一个电话号码:");

 string phone = Console.ReadLine();

 bool b = Regex.IsMatch(phone, @"^((\d{3,4}\-?\d{7,8})|(\d{5}))$");

 Console.WriteLine(b);

}
//=================================================================================================//字符串提取 Regex.Match() Regex.Matches()

 

//1,提取数字

 

//提取字符串中的所有的数字。

string str = "大家好呀,hello,2010年10月10日是个好日子。恩,9494.吼吼!886.";

//一般字符串提取的时候都不写^$,只有在做字符串匹配的时候才需要开始和结束。

//Regex.Match()该方法,无论在字符串中有多少个匹配项,都只找第一个匹配项返回。

Match match = Regex.Match(str, @"\d+");

if (match.Success)

{

//match.Value,获取匹配的字符串。

 Console.WriteLine(match.Value);

}

Console.WriteLine("ok");

Console.ReadKey();


//=================================================================================================
 //2,贪婪模式

 

string str = "1111。11。111。111111。";

 

//贪婪模式:在默认情况下会尽可能多的匹配

// 1也匹配.+ ; 1111。也匹配.+ ; 1111。11。111。111111。也匹配.+,这个时候会用最多的匹配。

Match match = Regex.Match(str, ".+");

Console.WriteLine(match.Value);//1111。11。111。111111。

Console.ReadKey();

//=================================================================================================
//3,终止贪婪模式

string str = "1111。11。111。111111。";

//在限定附后面使用?,表示终止贪婪模式,当终止贪婪模式后,会尽可能少的匹配。

Match match = Regex.Match(str, ".+?");

Console.WriteLine(match.Value);//1

Console.ReadKey();


//=================================================================================================
//正则表达式替换 Regex.Replace

 

//1,将hello ‘welcome’ to ‘China’ 替换成 hello 【welcome】 to 【China】

 

string str = "hello 'welcome' to 'China '.";

hello 【welcome】 to 【China】

//$1代表正则表达式内括号的索引,以1开始

str = Regex.Replace(str, "'(.+?)'", "【$1】");

Console.WriteLine(str);

Console.ReadKey();

//=================================================================================================

//2, 隐藏手机号码中间四位

 

string str = "中奖观众:13112345678,幸运奖:13489765439,参与奖:18657898764";

//对手机号用括号进行分组

str = Regex.Replace(str, @"(\d{3})\d{4}(\d{4})", "$1****$2");

Console.WriteLine(str);

Console.ReadKey();

 

posted @ 2013-10-23 10:12  豆豆0829  阅读(313)  评论(0编辑  收藏  举报