.NET下正則表達(dá)式應(yīng)用四例
1.確認(rèn)有效電子郵件格式
下面的代碼示例使用靜態(tài) Regex.IsMatch 方法驗(yàn)證一個(gè)字符串是否為有效電子郵件格式。如果字符串包含一個(gè)有效的電子郵件地址,則 IsValidEmail 方法返回 true,否則返回 false,但不采取其他任何操作。您可以使用 IsValidEmail,在應(yīng)用程序?qū)⒌刂反鎯?chǔ)在數(shù)據(jù)庫(kù)中或顯示在ASP.NET 頁(yè)中之前,篩選出包含無(wú)效字符的電子郵件地址。
Visual Basic代碼示例
Function IsValidEmail(strIn As String) As Boolean ' 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})(]?)$") End Function |
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.清理輸入字符串
下面的代碼示例使用靜態(tài) Regex.Replace 方法從字符串中抽出無(wú)效字符。您可以使用這里定義的 CleanInput 方法,清除掉在接受用戶(hù)輸入的窗體的文本字段中輸入的可能有害的字符。CleanInput 在清除掉除 @、-(連字符)和 .(句點(diǎn))以外的所有非字母數(shù)字字符后返回一個(gè)字符串。
Visual Basic代碼示例
Function CleanInput(strIn As String) As String ' Replace invalid characters with empty strings. Return Regex.Replace(strIn, "[^w.@-]", "") End Function |
C#代碼示例
String CleanInput(string strIn) { // Replace invalid characters with empty strings. return Regex.Replace(strIn, @"[^w.@-]", ""); } |
3.更改日期格式
以下代碼示例使用 Regex.Replace方法來(lái)用 dd-mm-yy 的日期形式代替 mm/dd/yy 的日期形式。
Visual Basic代碼示例
Function MDYToDMY(input As String) As String Return Regex.Replace(input, _ "b(?d{1,2})/(?d{1,2})/(?d{2,4})b", _ "${day}-${month}-${year}") End Function |
C#代碼示例
String MDYToDMY(String input) { return Regex.Replace(input, "\b(?\d{1,2})/(?\d{1,2})/(?\d{2,4})\b", "${day}-${month}-${year}"); } |
Regex替換模式
本示例說(shuō)明如何在 Regex.Replace 的替換模式中使用命名的反向引用。其中,替換表達(dá)式 ${day} 插入由 (?...) 組捕獲的子字符串。
有幾種靜態(tài)函數(shù)使您可以在使用正則表達(dá)式操作時(shí)無(wú)需創(chuàng)建顯式正則表達(dá)式對(duì)象,而 Regex.Replace 函數(shù)正是其中之一。如果您不想保留編譯的正則表達(dá)式,這將給您帶來(lái)方便
4.提取URL 信息
以下代碼示例使用Match.Result 來(lái)從URL提取協(xié)議和端口號(hào)。例如,“http://www.example.com:8080/letters/readme.html”將返回“http:8080”。
Visual Basic代碼示例
Function Extension(url As String) As String Dim r As New Regex("^(?w+)://[^/]+?(?:d+)?/", _ RegexOptions.Compiled) Return r.Match(url).Result("${proto}${port}") End Function |
C#代碼示例
String Extension(String url) { Regex r = new Regex(@"^(?w+)://[^/]+?(?:d+)?/", RegexOptions.Compiled); return r.Match(url).Result("${proto}${port}"); } |
【編輯推薦】