正則運算式是可以與輸入文本進行匹配的模式。.Net 框架提供了允許這種匹配的正則運算式引擎。模式由一個或多個字元文字,運算符或構造組成。
用於定義正則運算式的構造
有各種類型的字元,運算符和結構可以讓你定義正則運算式。 點擊下麵的鏈接來查看這些結構。
Regex類
Regex
類用於表示正則運算式,Regex
類有以下常用的方法:
編號 | 方法 | 描述 |
---|---|---|
1 | Public Function IsMatch (input As String) As Boolean |
指示在Regex 構造函數中指定的正則運算式是否在指定的輸入字串中找到匹配項。 |
2 | Public Function IsMatch (input As String, startat As Integer ) As Boolean |
指示在Regex 構造函數中指定的正則運算式是否在指定的輸入字串中找到匹配項,從字串中的指定起始位置開始匹配。 |
3 | Public Shared Function IsMatch (input As String, pattern As String ) As Boolean |
指示指定的正則運算式是否在指定的輸入字串中找到匹配項。 |
4 | Public Function Matches (input As String) As MatchCollection |
在指定的輸入字串中搜索正則運算式的所有匹配項。 |
5 | Public Function Replace (input As String, replacement As String) As String |
在指定的輸入字串中,用指定的替換字串替換與正則運算式模式匹配的所有字串。 |
6 | Public Function Split (input As String) As String |
在由Regex 構造函數中指定的正則運算式模式定義的位置處將輸入字串拆分為一個子字串數組。 |
有關方法和屬性的完整列表,請參閱Microsoft文檔。
1. 示例1
以下示例匹配以S
開頭的單詞:
Imports System.Text.RegularExpressions
Module regexProg
Sub showMatch(ByVal text As String, ByVal expr As String)
Console.WriteLine("The Expression: " + expr)
Dim mc As MatchCollection = Regex.Matches(text, expr)
Dim m As Match
For Each m In mc
Console.WriteLine(m)
Next m
End Sub
Sub Main()
Dim str As String = "A Thousand Splendid Suns"
Console.WriteLine("Matching words that start with 'S': ")
showMatch(str, "\bS\S*")
Console.ReadKey()
End Sub
End Module
執行上面示例代碼,得到以下結果 -
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
2. 示例2
以下示例匹配以m
開始並以e
結尾的單詞:
Imports System.Text.RegularExpressions
Module regexProg
Sub showMatch(ByVal text As String, ByVal expr As String)
Console.WriteLine("The Expression: " + expr)
Dim mc As MatchCollection = Regex.Matches(text, expr)
Dim m As Match
For Each m In mc
Console.WriteLine(m)
Next m
End Sub
Sub Main()
Dim str As String = "make a maze and manage to measure it"
Console.WriteLine("Matching words that start with 'm' and ends with 'e': ")
showMatch(str, "\bm\S*e\b")
Console.ReadKey()
End Sub
End Module
執行上面示例代碼,得到以下結果 -
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
3. 示例3
這個例子替換額外(多餘)的空白字元:
Imports System.Text.RegularExpressions
Module regexProg
Sub Main()
Dim input As String = "Hello World "
Dim pattern As String = "\\s+"
Dim replacement As String = " "
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)
Console.WriteLine("Original String: {0}", input)
Console.WriteLine("Replacement String: {0}", result)
Console.ReadKey()
End Sub
End Module
執行上面示例代碼,得到以下結果 -
Original String: Hello World
Replacement String: Hello World
上一篇:
VB.Net高級窗體
下一篇:
VB.Net資料庫訪問