VB.Net – 正则表达式
VB.Net – 正则表达式
甲正则表达式是可以针对一个输入文本相匹配的图案。.Net 框架提供了允许这种匹配的正则表达式引擎。模式由一个或多个字符文字、运算符或结构组成。
定义正则表达式的构造
有多种类型的字符、运算符和结构可让您定义正则表达式。单击以下链接以查找这些构造。
正则表达式类
Regex 类用于表示正则表达式。
Regex 类具有以下常用方法 –
| Sr.No. | 方法和说明 |
|---|---|
| 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