VB.Net - 正則表示式



正則表示式是一種可以與輸入文字匹配的模式。.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

以下示例匹配以“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

以下示例匹配以“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

此示例替換額外的空格:

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   
廣告
© . All rights reserved.