Regular Expression的基础学习(2)

ok,熟记Regular Expression语法后,继续学习其用法.
构造Regular Expression需要涉及Regex类,在Regex类中包括:IsMatch()、Replace()、Split()和Match方法;
(1)IsMatch()方法
 1public void Regex_Match()
 2{
 3    string strRegex = "^0771[-]\\d{7}$";
 4
 5    string strPhone_a = "07721234567";
 6    string strPhone_b = "07711234567";
 7
 8    Response.Write("该电话号码是否是南宁市正确的电话号码" + Regex.IsMatch(strPhone_a, strRegex));
 9    Response.Write("<br/>");
10    Response.Write("该电话号码是否是南宁市正确的电话号码" + Regex.IsMatch(strPhone_b, strRegex));
11}

(2)Replace()方法
插入一个官方文档的例子
 1public void Regex_Replace()
 2{
 3    string pattern = @"\s+";
 4    Regex rgx = new Regex(pattern);
 5
 6    // Declare a string consisting of text and white spaces.
 7    string inputStr = "a   b   c   d";
 8
 9    // Replace runs of white space in the input string with a
10    // comma and a blank.
11    string outputStr = rgx.Replace(inputStr, "");
12
13    // Display the resulting string.
14    Response.Write("Pattern: " + pattern + "<br />");
15    Response.Write("Input string: " + inputStr + "<br />");
16    Response.Write("Output string: "+ outputStr);
17}

(3)split()方法
 1public void Regex_Split()
 2{
 3    string strRegex = ";";
 4
 5    string strPhones = "0771-3830582;0772-3830582;0773-3830582;0774-3830582;0775-3830582;0776-3830582;0777-3830582;";
 6    string[] strPhonesc;
 7
 8    strPhonesc = Regex.Split(strPhones, strRegex);
 9
10    foreach(string str in strPhonesc)
11    {
12        Response.Write(str + "<br />");
13    }

14}

(4)重载
 1public void Regex_Reload()
 2{
 3    string strRegex = "^0771[-]\\d{7}$";
 4    Regex PhoneRegex = new Regex(strRegex, RegexOptions.None);
 5    if (PhoneRegex.IsMatch("07711234567"))
 6    {
 7        Response.Write("OK,Match");
 8    }

 9    else
10    {
11        Response.Write("Oh,Sorry");
12    }

13}
OK,大功告成~
posted @ 2007-12-11 14:28  CowboyRyan  阅读(223)  评论(0编辑  收藏  举报