C#正则表达式的使用

下面的代码示例使用静态 Regex.IsMatch 方法验证一个字符串是否为有效电子邮件格式。如果字符串包含一个有效的电子邮件地址,则 IsValidEmail 方法返回 true,否则返回 false,但不采取其他任何操作。您可以使用 IsValidEmail,在应用程序将地址存储在数据库中或显示在 ASP.NET 页中之前,筛选出包含无效字符的电子邮件地址。 

[C#]
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}

2//判断当前文本框是否正整数
public bool IsNumber(string sValue)
{
return
Regex.IsMatch(sValue, @"^[0-9]*[1-9][0-9]*$");
}

使用二:替换

2.清理输入字符串
下面的代码示例使用静态 Regex.Replace 方法从字符串中抽出无效字符。您可以使用这里定义的 CleanInput 方法,清除掉在接受用户输入的窗体的文本字段中输入的可能有害的字符。CleanInput 在清除掉除 @、-(连字符)和 .(句点)以外的所有非字母数字字符后返回一个字符串。

[C#]
String CleanInput(string strIn)
{
// Replace invalid characters with empty strings.
return Regex.Replace(strIn, @"[^\w\.@-]", "");
}

3.更改日期格式
以下代码示例使用 Regex.Replace 方法来用 dd-mm-yy 的日期形式代替 mm/dd/yy 的日期形式。

[C#]
String MDYToDMY(String input)
{
return Regex.Replace(input,
"\\b(?<month>\\d{1,2})/(?<day>\\d{1,2})/(?<year>\\d{2,4})\\b",
"${day}-${month}-${year}");
}
Regex 替换模式
本示例说明如何在 Regex.Replace 的替换模式中使用命名的反向引用。其中,替换表达式 ${day} 插入由 (?<day>...) 组捕获的子字符串。

有几种静态函数使您可以在使用正则表达式操作时无需创建显式正则表达式对象,而 Regex.Replace 函数正是其中之一。如果您不想保留编译的正则表达式,这将给您带来方便。

4
//替换
  public void Page1()
  {
   txtResult2.Text = "";
   try
   {
    Regex mRegex = new Regex(txtRegex2.Text);   
    txtResult2.Text = mRegex.Replace(txtStr2.Text,txtRegexRe.Text);
   }   
   catch(Exception e)
   {
    MessageBox.Show("输入的正则式错误,请重新输入!","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
   }
  }

使用三:查找

//查找
  public void Page2()
  {
   txtResult1.Text = "";
   try
   {   
    Regex mRegex = new Regex(txtRegex1.Text);
    MatchCollection mMactchCol = mRegex.Matches(txtStr1.Text);
    foreach(Match mMatch in mMactchCol)
    {
     txtResult1.Text += string.Format("{0} 在第{1}个字符被发现!\r\n",mMatch,mMatch.Index);
    }
    //分割
    string[] sArray = mRegex.Split(txtStr1.Text);
    txtSplit.Text = "";
    foreach(string sLine in sArray)
    {
     txtSplit.Text += sLine+"\r\n";
    }
   }
   catch(Exception e)
   {
    MessageBox.Show("输入的正则式错误,请重新输入!","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
   }
  }

使用四:提取 

 

//网页搜索检测
        public void Page3()
        {
            
string sRegex = "";
            
//1-根据关键词检索值来设定正则式
            try
            {                
                sRegex 
= GetRegex(txtRegex3.Text);
                
//MessageBox.Show(sRegex);
                Regex mRegex  = new Regex(sRegex);
                MatchCollection mMactchCol 
= mRegex.Matches(txtStr3.Text);//定位

                txtResult3.Text 
= "";
                LocData location;
                
foreach(Match mMatch in mMactchCol)
                {
                    
//直接定位到第i行
                    string[] sCodeArray = mMatch.ToString().Split(' ');
                    location 
= new LocData();
                    GetLocIndex(txtRegex3.Text,
ref location);
                    
if(location.nFindIndex == null)//无法定位
                    {
                        
return;
                    }
                    
else
                    {
                        
string sResult;
                        
for(int i=0;i<location.nFindIndex.Length;i++)
                        {
                            
string sTemp = sCodeArray[location.nFindIndex[i]];//得到定位行源代码-过滤其余部分
                            
//分割原定位行正则式
                            Regex mRegex1  = new Regex("\[\$\][^\$]*\[\^\$\]|\[\$\]");
                            
string[] sArray = mRegex1.Split(location.nFindeValue[i]);
                            
                            MatchCollection mMactchCol1 
= mRegex.Matches(txtStr3.Text);//定位
                        }
                    }
                    
break;
                }                
            }
            
catch(Exception e)
            {
                MessageBox.Show(
"输入的正则式错误,请重新输入!","警告",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }            
        }
        
//1-根据关键词检索值来设定正则式
        public string GetRegex(string sValue)
        {
            
string sRegex = "";
            Regex mRegex  
= new Regex("\[\$\][^\$]*\[\^\$\]|\[\$\]|\[~\][^~]*\[\^~\]|\[~\]");    
            
string[] sArray = mRegex.Split(sValue);//分割
            MatchCollection mMactchCol = mRegex.Matches(sValue);//定位
            int i = 0;
            Regex replaceReg  
= new Regex("(?<regex>[\[\]\.\^\$\{\}\(\)\|\*\+\?\\])");
            Regex replaceReg1 
= new Regex("\[\$\](?<regex>[^\$)]*)\[\^\$\]|\[~\](?<regex>[^~]*)\[\^~\]");

            
//将前面的字符串过滤特殊字符
            sArray[i] = replaceReg.Replace(sArray[i],"\${regex}");
            sRegex 
+= sArray[i];
            
            
foreach(Match mMatch in mMactchCol)
            {                
                
//将本查找项替换
                if(mMatch.ToString() == "[$]" || mMatch.ToString() == "[~]")
                    sRegex 
+= "(\w|\W)*";//任意字符串,不带换行符
                else
                {                    
                    
string sTemp = replaceReg1.Replace(mMatch.ToString(),"${regex}");
                    sRegex 
+= sTemp;//任意字符串
                }
                
                
//将后面的字符串过滤特殊字符
                i++;
                sArray[i] 
= replaceReg.Replace(sArray[i],"\${regex}");
                sRegex 
+= sArray[i];
            }
            
return sRegex;
        }
        
//2-得到行定位数组
        public void GetLocIndex(string sValue,ref LocData location)
        {
            
int[] nFindIndex;
            
string[] nFindValue;
            
string[] sLineArray = sValue.Split(' ');
            Regex mRegex  
= new Regex("\[\$\][^\$]*\[\^\$\]|\[\$\]");
            
string sSaveIndex = "";
            
string sSaveValue = "";
            
for(int i =0 ; i< sLineArray.Length ; i++)
            {
                
if(mRegex.IsMatch(sLineArray[i]))
                {
                    
if(sSaveIndex != "")
                    {
                        sSaveIndex 
+= " "+i.ToString();
                        sSaveValue 
+= " "+sLineArray[i];
                    }
                    
else
                    {
                        sSaveIndex 
+= i.ToString();
                        sSaveValue 
+= sLineArray[i];
                    }
                }
            }
            
//有返回
            string[] sTemp1;
            
string[] sTemp2;
            
if(sSaveIndex != "")
            {
                sTemp1 
= sSaveIndex.Split(' ');
                sTemp2 
= sSaveValue.Split(' ');
                
if(sTemp1.Length != 0)
                {
                    nFindIndex 
= new int[sTemp1.Length];
                    nFindValue 
= new string[sTemp1.Length];
                    
for(int i=0;i<sTemp1.Length;i++)
                    {
                        nFindIndex[i] 
= Convert.ToInt16(sTemp1[i]);
                        nFindValue[i] 
= sTemp2[i];
                    }
                    location.nFindIndex 
= nFindIndex;
                    location.nFindeValue
= nFindValue;
                }                
            }
            
else
            {
                nFindIndex 
= null;
                nFindValue 
= null;
            }
        }

    }

 

 

 

//汉字转换成网页格式
public string GetCurURL(int nIndex)
        {
            
string sURL;
            
if (m_URLright == null)
                sURL 
= m_URLleft;
            
else
            {
                
int nPage = m_nBase + (nIndex - 1* m_nStep;
                sURL 
= string.Format(m_URLleft + "{0}" + m_URLright, nPage.ToString());
            }

            
//注意:URL中的汉字要进行GB2312编码,否则会出现错误                
            Regex myRegex = new Regex("[\u4e00-\u9fa5]");
            MatchCollection myMatchObject 
= myRegex.Matches(sURL);
            
foreach (Match sMatch in myMatchObject)
            {
                
string sGBchar = sMatch.ToString();
                
string sUnicode = System.Web.HttpUtility.UrlEncode(sGBchar, System.Text.Encoding.GetEncoding("GB2312"));
                sURL 
= sURL.Replace(sGBchar, sUnicode);
            }
            
return sURL;
        }
//从网页中得到链接数组
        public string[] GetURLFromFile(string sPath, long FWID)
        {
            
//读txt文件            
            
//string sPath = Environment.CurrentDirectory+"\temp\"+sFileName;
            StreamReader sReader;
            sReader 
= File.OpenText(sPath);

            
string sLinkSecond = "";
            
string strLine = "";

            
//所有链接正则式
            
//Regex myRegex = new Regex( "http://([w-]+.)+[w-]+(/[w-   ./?%&=]*)?");
            
//"<a[^>]+href=\s*(?:'(?<href>[^'']+)'|''(?<href>[^'']+)''|(?<href>[^>\s]+))\s*[^>]*>");
            Regex[] myRex = new Regex[m_searchTree.Length];
            
int nIndex = 0;
            
for (int i = 0; i < m_searchTree.Length; i++)
            {
                
if (m_searchTree[i].lFWID == FWID)
                {
                    Globel.NodeData nData 
= (Globel.NodeData)m_searchTree[i].Tag;
                    
//找到2级网页地址
                    myRex[nIndex] = new Regex(nData.sRegex);
                    nIndex
++;
                }
            }

            
string[] sLinkArray = null;
            
bool bRepeated;
            
while (sReader.Peek() != -1)
            {
                
//读取一行源代码
                strLine = sReader.ReadLine();
                
if (strLine == null)
                {
                    
break;
                }
                
else
                {
                    strLine 
= strLine.Trim();
                    
//非空
                    if (strLine != "")
                    {
                        
for (int i = 0; myRex[i] != null; i++)
                        {
                            MatchCollection myMatchObject 
= myRex[i].Matches(strLine);
                            
foreach (Match sMatch in myMatchObject)
                            {
                                
string sTempLink = sMatch.ToString();
                                
//过滤重复链接
                                if (sLinkArray != null)
                                {
                                    bRepeated 
= false;
                                    
for (int j = 0; j < sLinkArray.Length; j++)
                                    {
                                        
if (sTempLink == sLinkArray[j])
                                        {
                                            bRepeated 
= true;
                                            
break;
                                        }
                                    }
                                    
if (bRepeated)
                                        
continue;
                                }
                                
if (sLinkSecond == "")
                                    sLinkSecond 
+= sTempLink;
                                
else
                                    sLinkSecond 
+= " " + sTempLink;
                                sLinkArray 
= sLinkSecond.Split(' ');
                            }
                        }
                    }
                }
            }

            sReader.Close();
            
return sLinkArray;
        }
//保存网页-方式1:WebClient
        public bool SaveWebPage1(string sURL, string sPath)
        {
            
try
            {
                WebClient wc 
= new WebClient();
                
//下载方式1
                wc.DownloadFile(sURL, sPath);

                
/*下载方式2
                byte[]   data   =   wc.DownloadData(sURL);
                string   HtmlCode   =   Encoding.UTF8.GetString(data,0,data.Length);
                wc.Dispose();
                m_sHtmlCode = HtmlCode;    
                
*/
            }
            
catch (Exception ex)
            {
                
return false;
            }
            
return true;
        }
        
//方式2:WebRequest
        public bool SaveWebPage2(string sURL)
        {
            HttpWebRequest request 
= (HttpWebRequest)WebRequest.Create(sURL);
            HttpWebResponse response 
= (HttpWebResponse)request.GetResponse();
            Stream stream 
= response.GetResponseStream();

            
string buffer = "", line;
            StreamReader reader 
= new StreamReader(stream);
            
while ((line = reader.ReadLine()) != null)
            {
                buffer 
+= line + " ";
            }

            SaveTextFile(buffer);
            
return true;
        }
        
//保存文本文件
        public void SaveTextFile(string buffer)
        {
            
string filename = "temp.html";
            StreamWriter outStream 
= new StreamWriter(filename);
            outStream.Write(buffer);
            outStream.Close();
        }

 

 

常用正则表达式:

匹配中文字符的正则表达式: [\u4e00-\u9fa5]

匹配双字节字符(包括汉字在内):[^\x00-\xff]

应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1)

String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;}

匹配空行的正则表达式:\n[\s| ]*\r

匹配HTML标记的正则表达式:/<(.*)>.*<\/\1>|<(.*) \/>/

匹配首尾空格的正则表达式:(^\s*)|(\s*$)

应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现,如下:

应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现,如下:

String.prototype.trim = function()
{
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

利用正则表达式分解和转换IP地址:

下面是利用正则表达式匹配IP地址,并将IP地址转换成对应数值的javascript程序:

function IP2V(ip)
{
 re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g  //匹配IP地址的正则表达式
if(re.test(ip))
{
return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1
}
else
{
 throw new Error("Not a valid IP address!")
}
}

不过上面的程序如果不用正则表达式,而直接用split函数来分解可能更简单,程序如下:

var ip="10.100.20.168"
ip=ip.split(".")
alert("IP值是:"+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))

匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*

匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

 补充:
^\d+$  //匹配非负整数(正整数 + 0)
^[0-9]*[1-9][0-9]*$  //匹配正整数
^((-\d+)|(0+))$  //匹配非正整数(负整数 + 0)
^-[0-9]*[1-9][0-9]*$  //匹配负整数
^-?\d+$    //匹配整数
^\d+(\.\d+)?$  //匹配非负浮点数(正浮点数 + 0)
^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$  //匹配正浮点数
^((-\d+(\.\d+)?)|(0+(\.0+)?))$  //匹配非正浮点数(负浮点数 + 0)
^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$  //匹配负浮点数
^(-?\d+)(\.\d+)?$  //匹配浮点数
^[A-Za-z]+$  //匹配由26个英文字母组成的字符串
^[A-Z]+$  //匹配由26个英文字母的大写组成的字符串
^[a-z]+$  //匹配由26个英文字母的小写组成的字符串
^[A-Za-z0-9]+$  //匹配由数字和26个英文字母组成的字符串
^\w+$  //匹配由数字、26个英文字母或者下划线组成的字符串
^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$    //匹配email地址
^[a-zA-z]+://匹配(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$  //匹配url

链接的提取主要使用正则表达式,如下:
<a[^>]+href=\s*(?:'(?<href>[^'']+)'|""(?<href>[^""]+)""|(?<href>[^>\s]+))\s*[^>]*>

匹配网页中以htm为结尾的超链接
string ss ="<A\s+href=""(http|https|ftp|rtsp|mms):(\/\/|\\\\){1}(([A-Za-z0-9_-])+[.]){1,}(net|com|cn|org|cc|tv|[0-9]{1,3})(\S*\/)((\S)+[.]{1}(htm)))""\s+target=_blank>(.*)</A>"

正则式基础知识:

代表任意字符的正则表达式:(\w|\W)*

代表单行所有字符的正则表达式: (.*)

\s代表任何空格字符:比如一个空格或者tab

\d表示任何数字

5+任意数目个字符5
(52)+7

[a-f] 任何从'a'到'f'(小写)的单个字符

* 7*8前一个字符/子表达式可以出现0次或多次-8/778
+ 7+8前可出现1次或多次 -778
() 分组
| 8|6两个中的任何一个都匹配
[] 匹配一组中的-个-[A-C]可以匹配A,B,C
[^] 匹配的字符不在所给范围内 [^A-B]匹配A,B之外的任何
. 除换行以外的任何字符 .here匹配where there
\s 任何空格字符
\S 任何非空格字符
\d 任何数字字符
\D 任何非数字字符
\w 任何"词"字符(字母,数字或下划线)
网页标签匹配 <title>[\s\S]*?</title>

posted @ 2008-01-24 07:04  sig556  阅读(4979)  评论(0编辑  收藏  举报