Visual Basic 正则表达式

正则表达式 是可以与输入文本匹配的模式。.Net framework 提供了支持此类匹配的正则表达式引擎。模式由一个或多个字符文本、运算符或构造组成。


用于定义正则表达式的构造

有各种类型的字符、运算符和结构可用于定义正则表达式。

单击以下链接以查看更详细的信息:


Regex 类

Regex 类用于表示正则表达式。

Regex 类有以下常用方法:

编号方法 & 描述
1

Public Function IsMatch (input As String) As Boolean

表示正则表达式构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项。

2

Public Function IsMatch (input As String, startat As Integer ) As Boolean

表示正则表达式构造函数中指定的正则表达式是否在指定的输入字符串中找到匹配项,从字符串中指定的起始位置开始。

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()

在正则表达式构造函数中指定的正则表达式模式定义的位置,将输入字符串拆分为子字符串数组。

有关方法和属性的完整列表,请参考 Microsoft 文档


实例 1

以下实例匹配以 'S' 开头的单词:

  1. Imports System.Text.RegularExpressions
  2. Module regexProg
  3. Sub showMatch(ByVal text As String, ByVal expr As String)
  4. Console.WriteLine("The Expression: " + expr)
  5. Dim mc As MatchCollection = Regex.Matches(text, expr)
  6. Dim m As Match
  7. For Each m In mc
  8. Console.WriteLine(m)
  9. Next m
  10. End Sub
  11. Sub Main()
  12. Dim str As String = "A Thousand Splendid Suns"
  13. Console.WriteLine("Matching words that start with 'S': ")
  14. showMatch(str, "\bS\S*")
  15. Console.ReadKey()
  16. End Sub
  17. End Module

结果如下:

  1. Matching words that start with 'S':
  2. The Expression: \bS\S*
  3. Splendid
  4. Suns

实例 2

以下实例匹配以 'm' 开头、以 'e' 结尾的单词:

  1. Imports System.Text.RegularExpressions
  2. Module regexProg
  3. Sub showMatch(ByVal text As String, ByVal expr As String)
  4. Console.WriteLine("The Expression: " + expr)
  5. Dim mc As MatchCollection = Regex.Matches(text, expr)
  6. Dim m As Match
  7. For Each m In mc
  8. Console.WriteLine(m)
  9. Next m
  10. End Sub
  11. Sub Main()
  12. Dim str As String = "make a maze and manage to measure it"
  13. Console.WriteLine("Matching words that start with 'm' and ends with 'e': ")
  14. showMatch(str, "\bm\S*e\b")
  15. Console.ReadKey()
  16. End Sub
  17. End Module

结果如下:

  1. Matching words start with 'm' and ends with 'e':
  2. The Expression: \bm\S*e\b
  3. make
  4. maze
  5. manage
  6. measure

实例 3

此实例替换额外的空白:

  1. Imports System.Text.RegularExpressions
  2. Module regexProg
  3. Sub Main()
  4. Dim input As String = "Hello World "
  5. Dim pattern As String = "\\s+"
  6. Dim replacement As String = " "
  7. Dim rgx As Regex = New Regex(pattern)
  8. Dim result As String = rgx.Replace(input, replacement)
  9. Console.WriteLine("Original String: {0}", input)
  10. Console.WriteLine("Replacement String: {0}", result)
  11. Console.ReadKey()
  12. End Sub
  13. End Module

结果如下:

  1. Original String: Hello World
  2. Replacement String: Hello World