VB.Net正則表達式

正則表達式是可以與輸入文本進行匹配的模式。*.Net* 框架提供了允許這種匹配的正則表達式引擎。模式由一個或多個字符文字,運算符或構造組成。

用於定義正則表達式的構造

有各種類型的字符,運算符和結構可以讓你定義正則表達式。 點擊下面的鏈接來查看這些結構。

  • 字符轉義
  • Character類
  • 錨定
  • 分組結構
  • 量詞
  • 反向引用結構
  • 交替結構
  • 替換結構
  • 雜項結構

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