正規表示式是可以與輸入文字進行匹配的模式。.Net 框架提供了允許這種匹配的正規表示式引擎。模式由一個或多個字元文字,運算子或構造組成。
有各種型別的字元,運算子和結構可以讓你定義正規表示式。 點選下面的連結來檢視這些結構。
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文件。
以下範例匹配以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
以下範例匹配以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
這個例子替換額外(多餘)的空格符:
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