vb.net 正则表达式匹配字符串的多种实例方法
时间: 2023-08-15 22:04:50 浏览: 278
在 VB.NET 中,可以使用 `System.Text.RegularExpressions.Regex` 类来进行正则表达式匹配。以下是几种常见的实例方法:
1. `IsMatch(input As String, pattern As String)`:判断给定的字符串 `input` 是否匹配正则表达式 `pattern`,返回布尔值。
```vb.net
Dim input As String = "Hello, World!"
Dim pattern As String = "^H.*d!$"
Dim match As Boolean = Regex.IsMatch(input, pattern)
Console.WriteLine(match) ' True
```
2. `Match(input As String, pattern As String)`:在给定的字符串 `input` 中查找第一个匹配正则表达式 `pattern` 的子串,返回 `Match` 对象。
```vb.net
Dim input As String = "abc123def456"
Dim pattern As String = "\d+"
Dim match As Match = Regex.Match(input, pattern)
Console.WriteLine(match.Value) ' 123
```
3. `Matches(input As String, pattern As String)`:在给定的字符串 `input` 中查找所有匹配正则表达式 `pattern` 的子串,返回 `MatchCollection` 对象。
```vb.net
Dim input As String = "abc123def456"
Dim pattern As String = "\d+"
Dim matches As MatchCollection = Regex.Matches(input, pattern)
For Each match As Match In matches
Console.WriteLine(match.Value)
Next
' 123
' 456
```
4. `Replace(input As String, pattern As String, replacement As String)`:将给定的字符串 `input` 中所有匹配正则表达式 `pattern` 的子串替换为 `replacement`,返回替换后的字符串。
```vb.net
Dim input As String = "cat, dog, cat, dog"
Dim pattern As String = "cat"
Dim replacement As String = "bird"
Dim result As String = Regex.Replace(input, pattern, replacement)
Console.WriteLine(result) ' bird, dog, bird, dog
```
以上是 VB.NET 中常见的几种正则表达式匹配字符串的实例方法,通过灵活应用这些方法可以解决很多字符串处理问题。
阅读全文