VBScript正则表达式从入门到精通 详解核心语法与实战应用技巧 解决文本处理难题

引言:为什么需要学习VBScript正则表达式?
在日常的文本处理工作中,我们经常需要从大量的文本中提取特定信息、验证格式、替换内容或进行复杂的字符串匹配。传统的字符串函数如
InStr
、
Left
、
Right
、
Mid
虽然能处理简单的任务,但面对复杂的模式匹配时就显得力不从心。
VBScript正则表达式(Regular Expression)正是解决这类问题的利器。它是一种强大的文本模式匹配工具,能够用简洁的语法描述复杂的字符串模式。通过正则表达式,我们可以:
快速验证用户输入的格式是否正确(如邮箱、电话号码)
从日志文件中提取关键信息
批量替换文本中的特定模式
检查代码中的潜在问题
处理结构化数据(如CSV、JSON、XML)
本文将从基础语法讲起,逐步深入到高级应用,通过大量实例帮助你掌握VBScript正则表达式的核心技巧,最终能够独立解决各种文本处理难题。
VBScript正则表达式基础
1. 正则表达式对象创建
在VBScript中,使用正则表达式首先需要创建
RegExp
对象:
‘ 方法1:使用CreateObject创建
Dim regex
Set regex = CreateObject(“VBScript.RegExp”)

‘ 方法2:使用New关键字(如果支持)
‘ Dim regex
‘ Set regex = New RegExp

‘ 设置基本属性
regex.Pattern = “your_pattern_here” ‘ 正则表达式模式
regex.IgnoreCase = True ‘ 忽略大小写
regex.Global = True ‘ 全局匹配
regex.Multiline = False ‘ 多行模式
2. RegExp对象的核心属性和方法
核心属性:
Pattern
:正则表达式模式字符串
IgnoreCase
:布尔值,是否忽略大小写
Global
:布尔值,是否进行全局匹配(查找所有匹配而非第一个)
Multiline
:布尔值,是否多行模式(影响^和$的行为)
核心方法:
Test(String)
:测试字符串是否匹配模式,返回True/False
Execute(String)
:执行匹配,返回MatchCollection对象
Replace(String, replacement)
:替换匹配的文本
Split(String)
:根据匹配分割字符串
3. 第一个正则表达式示例
让我们从一个简单的例子开始:匹配一个简单的邮箱地址。
Sub SimpleEmailValidation()
Dim regex, testEmails, email, match

‘ 创建正则表达式对象
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^\w+@\w+\.\w+$” ‘ 简单的邮箱模式
regex.IgnoreCase = True

‘ 测试邮箱列表
testEmails = Array(“user@example.com”, “invalid-email”, “user@domain”, “test@site.org”)

For Each email In testEmails
If regex.Test(email) Then
WScript.Echo “有效邮箱: ” & email
Else
WScript.Echo “无效邮箱: ” & email
End If
Next
End Sub

‘ 调用示例
‘ Call SimpleEmailValidation()
这个例子展示了正则表达式的基本用法:创建对象、设置模式、执行测试。虽然这个邮箱验证很简单,但它演示了核心流程。
正则表达式核心语法详解
1. 元字符(Metacharacters)
元字符是正则表达式中具有特殊含义的字符:
元字符
描述
示例
.
匹配除换行符外的任意单个字符
a.c
匹配 “abc”, “aac”, “a c”
^
匹配字符串的开始
^Hello
匹配以Hello开头的字符串
$
匹配字符串的结束
world$
匹配以world结尾的字符串
*
匹配前一个字符0次或多次
ab*c
匹配 “ac”, “abc”, “abbc”
+
匹配前一个字符1次或多次
ab+c
匹配 “abc”, “abbc”,不匹配 “ac”
?
匹配前一个字符0次或1次
colou?r
匹配 “color” 和 “colour”
\
转义字符,用于匹配特殊字符
\.
匹配实际的点号
|
或运算符
cat|dog
匹配 “cat” 或 “dog”
()
分组,捕获组
(ab)+
匹配 “ab”, “abab”
[]
字符类,匹配方括号内的任意字符
[aeiou]
匹配任意元音字母
{}
量词,指定匹配次数
a{2,4}
匹配 “aa”, “aaa”, “aaaa”
2. 字符类(Character Classes)
字符类允许你匹配一组特定的字符:
Sub CharacterClassExamples()
Dim regex, testStrings, str

Set regex = CreateObject(“VBScript.RegExp”)
regex.IgnoreCase = True

‘ 示例1:匹配元音字母
regex.Pattern = “[aeiou]”
testStrings = Array(“hello”, “rhythm”, “sky”, “audio”)
WScript.Echo “=== 匹配元音字母 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 包含元音”
Next

‘ 示例2:匹配数字
regex.Pattern = “\d” ‘ 等价于 [0-9]
testStrings = Array(“abc123”, “no numbers”, “year2024”)
WScript.Echo vbCrLf & “=== 匹配数字 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 包含数字”
Next

‘ 示例3:匹配字母数字和下划线(常用于标识符)
regex.Pattern = “\w” ‘ 等价于 [a-zA-Z0-9_]
testStrings = Array(“var_name”, “123”, “!@#”)
WScript.Echo vbCrLf & “=== 匹配单词字符 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 包含单词字符”
Next
End Sub
3. 量词(Quantifiers)
量词用于指定匹配的次数:
Sub QuantifierExamples()
Dim regex, testStrings, str, matches, match

Set regex = CreateObject(“VBScript.RegExp”)
regex.Global = True

‘ 示例1:匹配至少3个连续的a
regex.Pattern = “a{3,}”
testStrings = Array(“aa”, “aaa”, “aaaa”, “baaab”)
WScript.Echo “=== 至少3个a ===”
For Each str In testStrings
Set matches = regex.Execute(str)
If matches.Count > 0 Then
WScript.Echo str & ” -> 匹配: ” & matches(0).Value
End If
Next

‘ 示例2:匹配2-4个数字
regex.Pattern = “\d{2,4}”
testStrings = Array(“1”, “12”, “123”, “1234”, “12345”)
WScript.Echo vbCrLf & “=== 2-4个数字 ===”
For Each str In testStrings
Set matches = regex.Execute(str)
If matches.Count > 0 Then
WScript.Echo str & ” -> 匹配: ” & matches(0).Value
End If
Next

‘ 示例3:匹配可选的s
regex.Pattern = “colou?r”
testStrings = Array(“color”, “colour”, “colouur”)
WScript.Echo vbCrLf & “=== 可选的u ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 匹配”
Next
End Sub
4. 分组与捕获(Grouping and Capturing)
分组允许你将多个字符作为一个单元处理,并捕获匹配的子字符串:
Sub GroupingExamples()
Dim regex, testStrings, str, matches, match, submatches

Set regex = CreateObject(“VBScript.RegExp”)
regex.Global = True

‘ 示例1:捕获日期的年、月、日
regex.Pattern = “(\d{4})-(\d{2})-(\d{2})”
testStrings = Array(“2024-01-15”, “2023-12-25”, “2024-13-45”)
WScript.Echo “=== 捕获日期组件 ===”
For Each str In testStrings
Set matches = regex.Execute(str)
If matches.Count > 0 Then
Set match = matches(0)
WScript.Echo “完整匹配: ” & match.Value
WScript.Echo “年: ” & match.SubMatches(0)
WScript.Echo “月: ” & match.SubMatches(1)
WScript.Echo “日: ” & match.SubMatches(2)
WScript.Echo “—”
End If
Next

‘ 示例2:命名捕获组(VBScript不支持命名组,但可以用位置)
regex.Pattern = “(\w+)=(\d+)”
testStrings = Array(“score=95”, “age=25”, “invalid”)
WScript.Echo vbCrLf & “=== 键值对捕获 ===”
For Each str In testStrings
Set matches = regex.Execute(str)
If matches.Count > 0 Then
Set match = matches(0)
WScript.Echo “键: ” & match.SubMatches(0) & “, 值: ” & match.SubMatches(1)
End If
Next
End Sub
5. 边界匹配(Anchors and Boundaries)
边界匹配用于指定匹配的位置:
Sub BoundaryExamples()
Dim regex, testStrings, str

Set regex = CreateObject(“VBScript.RegExp”)
regex.IgnoreCase = True

‘ 示例1:匹配以特定单词开头
regex.Pattern = “^Dear”
testStrings = Array(“Dear John”, “Hello Dear”, “Dearly”)
WScript.Echo “=== 以Dear开头 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 匹配”
Next

‘ 示例2:匹配以特定单词结尾
regex.Pattern = “end$”
testStrings = Array(“the end”, “friend”, “bend”)
WScript.Echo vbCrLf & “=== 以end结尾 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 匹配”
Next

‘ 示例3:单词边界
regex.Pattern = “\bcat\b” ‘ 匹配独立的单词”cat”
testStrings = Array(“cat”, “concatenate”, “scatter”, “a cat”)
WScript.Echo vbCrLf & “=== 单词边界 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 匹配”
Next
End Sub
6. 特殊字符和转义
Sub EscapeExamples()
Dim regex, testStrings, str

Set regex = CreateObject(“VBScript.RegExp”)

‘ 示例1:匹配实际的点号(而不是任意字符)
regex.Pattern = “\d+\.\d+” ‘ 匹配浮点数
testStrings = Array(“3.14”, “abc”, “123.45”, “123”)
WScript.Echo “=== 匹配浮点数 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 是浮点数”
Next

‘ 示例2:匹配特殊字符
regex.Pattern = “\$\d+” ‘ 匹配美元金额
testStrings = Array(“$100”, “100”, “$200.50”)
WScript.Echo vbCrLf & “=== 匹配美元金额 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 匹配”
Next

‘ 示例3:匹配反斜杠
regex.Pattern = “C:\\\\” ‘ 匹配”C:\”
testStrings = Array(“C:\Windows”, “C:/Windows”, “C:\”)
WScript.Echo vbCrLf & “=== 匹配路径 ===”
For Each str In testStrings
If regex.Test(str) Then WScript.Echo str & ” 匹配”
Next
End Sub
RegExp对象的三大方法详解
1. Test方法:快速验证
Test
方法用于快速检查字符串是否匹配模式,返回布尔值:
Sub TestMethodDemo()
Dim regex, inputs, input

Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^\d{3}-\d{3}-\d{4}$” ‘ 美国电话号码格式
regex.IgnoreCase = True

inputs = Array(“123-456-7890”, “123-45-6789”, “1234567890”, “123-456-789”)

WScript.Echo “=== 电话号码验证 ===”
For Each input In inputs
If regex.Test(input) Then
WScript.Echo “✓ ” & input & ” 是有效的电话号码”
Else
WScript.Echo “✗ ” & input & ” 是无效的电话号码”
End If
Next
End Sub
2. Execute方法:获取所有匹配
Execute
方法返回一个
MatchCollection
对象,包含所有匹配项:
Sub ExecuteMethodDemo()
Dim regex, text, matches, match, i

Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “#\w+” ‘ 匹配主题标签
regex.Global = True

text = “Hello #world, this is a #test message with #multiple tags”

Set matches = regex.Execute(text)

WScript.Echo “找到 ” & matches.Count & ” 个匹配:”
For i = 0 To matches.Count – 1
Set match = matches(i)
WScript.Echo ” ” & (i + 1) & “. ” & match.Value & ” (位置: ” & match.FirstIndex & “)”
Next
End Sub
3. Replace方法:智能替换
Replace
方法用于替换匹配的文本,支持反向引用:
Sub ReplaceMethodDemo()
Dim regex, text, result

Set regex = CreateObject(“VBScript.RegExp”)

‘ 示例1:简单的替换
regex.Pattern = “error”
regex.Global = True
text = “error found: error in line 1, another error”
result = regex.Replace(text, “bug”)
WScript.Echo “示例1: ” & result

‘ 示例2:使用捕获组进行替换
regex.Pattern = “(\d{4})-(\d{2})-(\d{2})”
text = “日期: 2024-01-15”
‘ 使用$1, $2, $3引用捕获组
result = regex.Replace(text, “$2/$3/$1”)
WScript.Echo “示例2: ” & result

‘ 示例3:格式化电话号码
regex.Pattern = “(\d{3})(\d{3})(\d{4})”
text = “电话: 1234567890”
result = regex.Replace(text, “($1) $2-$3”)
WScript.Echo “示例3: ” & result

‘ 示例4:删除重复空格
regex.Pattern = “\s+”
regex.Global = True
text = “Hello World from VBScript”
result = regex.Replace(text, ” “)
WScript.Echo “示例4: ” & result
End Sub
4. Split方法:智能分割
Split
方法根据正则表达式匹配分割字符串:
Sub SplitMethodDemo()
Dim regex, text, parts, part, i

Set regex = CreateObject(“VBScript.RegExp”)
regex.Global = True

‘ 示例1:按多个分隔符分割
regex.Pattern = “[,;\s]+” ‘ 逗号、分号或空格
text = “apple,banana;orange grape”
parts = regex.Split(text)
WScript.Echo “示例1: 按[,;\\s+]分割”
For i = 0 To UBound(parts)
WScript.Echo ” [” & i & “] = ” & parts(i)
Next

‘ 示例2:按数字分割
regex.Pattern = “\d+”
text = “item123quantity456price”
parts = regex.Split(text)
WScript.Echo vbCrLf & “示例2: 按数字分割”
For i = 0 To UBound(parts)
WScript.Echo ” [” & i & “] = ” & parts(i)
Next

‘ 示例3:分割CSV(处理引号内的逗号)
regex.Pattern = “,(?=(?:[^””]*””[^””]*””)*[^””]*$)”
text = “Name,Age,””City, State””,Country”
parts = regex.Split(text)
WScript.Echo vbCrLf & “示例3: 智能CSV分割”
For i = 0 To UBound(parts)
WScript.Echo ” [” & i & “] = ” & parts(i)
Next
End Sub
实战应用技巧
1. 邮箱地址验证
Function IsValidEmail(email)
Dim regex
Set regex = CreateObject(“VBScript.RegExp”)
‘ RFC 5322 简化版
regex.Pattern = “^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$”
regex.IgnoreCase = True
IsValidEmail = regex.Test(email)
End Function

Sub EmailValidationDemo()
Dim emails, email

emails = Array(“user@example.com”, “user.name+tag@domain.co.uk”, _
“invalid@domain”, “@domain.com”, “user@.com”, _
“user@domain”, “user@domain.c”, “user@domain.com”)

WScript.Echo “=== 邮箱验证测试 ===”
For Each email In emails
If IsValidEmail(email) Then
WScript.Echo “✓ ” & email
Else
WScript.Echo “✗ ” & email
End If
Next
End Sub
2. 电话号码格式化
Function FormatPhoneNumber(phone)
Dim regex
Set regex = CreateObject(“VBScript.RegExp”)

‘ 移除所有非数字字符
regex.Pattern = “\D”
phone = regex.Replace(phone, “”)

‘ 根据长度格式化
Select Case Len(phone)
Case 10 ‘ 美国标准
regex.Pattern = “(\d{3})(\d{3})(\d{4})”
FormatPhoneNumber = regex.Replace(phone, “($1) $2-$3”)
Case 11 ‘ 带国家代码
regex.Pattern = “(\d{1})(\d{3})(\d{3})(\d{4})”
FormatPhoneNumber = regex.Replace(phone, “+$1 ($2) $3-$4”)
Case Else
FormatPhoneNumber = phone
End Select
End Function

Sub PhoneFormattingDemo()
Dim phones, phone

phones = Array(“1234567890”, “123-456-7890”, “1-800-555-1212”, “12345678”)

WScript.Echo “=== 电话号码格式化 ===”
For Each phone In phones
WScript.Echo phone & ” -> ” & FormatPhoneNumber(phone)
Next
End Sub
3. 日志文件解析
Sub ParseLogFile(logContent)
Dim regex, matches, match, i

‘ 匹配日志行:[时间] [级别] 消息
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “\[(\d{2}:\d{2}:\d{2})\]\s+\[(\w+)\]\s+(.+)”
regex.Global = True

Set matches = regex.Execute(logContent)

WScript.Echo “解析到 ” & matches.Count & ” 条日志记录:”
For i = 0 To matches.Count – 1
Set match = matches(i)
WScript.Echo “时间: ” & match.SubMatches(0) & _
” | 级别: ” & match.SubMatches(1) & _
” | 消息: ” & match.SubMatches(2)
Next
End Sub

Sub LogParsingDemo()
Dim logContent
logContent = “[10:30:15] [INFO] Application started” & vbCrLf & _
“[10:30:20] [ERROR] Database connection failed” & vbCrLf & _
“[10:30:25] [WARN] High memory usage detected” & vbCrLf & _
“[10:30:30] [INFO] Processing completed”

Call ParseLogFile(logContent)
End Sub
4. HTML/XML内容提取
Sub ExtractHTMLContent()
Dim regex, html, matches, match, i

html = “

Title

Paragraph 1

Paragraph 2

”

‘ 提取所有

标签内容
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “

(.*?)

”
regex.Global = True
regex.IgnoreCase = True

Set matches = regex.Execute(html)

WScript.Echo “提取到的段落:”
For i = 0 To matches.Count – 1
Set match = matches(i)
WScript.Echo ” ” & (i + 1) & “. ” & match.SubMatches(0)
Next

‘ 提取所有标签名
regex.Pattern = “<(\w+)>”
Set matches = regex.Execute(html)
WScript.Echo vbCrLf & “找到的标签:”
For i = 0 To matches.Count – 1
WScript.Echo ” ” & matches(i).SubMatches(0)
Next
End Sub
5. 数据清洗和标准化
Function CleanAndNormalizeText(text)
Dim regex

Set regex = CreateObject(“VBScript.RegExp”)
regex.Global = True

‘ 1. 删除多余的空格
regex.Pattern = “\s+”
text = regex.Replace(text, ” “)

‘ 2. 删除首尾空格
text = Trim(text)

‘ 3. 标准化标点符号(删除多余空格)
regex.Pattern = “\s*([.,!?;:])\s*”
text = regex.Replace(text, “$1”)

‘ 4. 删除特殊字符(保留字母、数字、基本标点)
regex.Pattern = “[^a-zA-Z0-9\s.,!?;:’-]”
text = regex.Replace(text, “”)

‘ 5. 大写首字母
If Len(text) > 0 Then
text = UCase(Left(text, 1)) & Mid(text, 2)
End If

CleanAndNormalizeText = text
End Function

Sub TextCleaningDemo()
Dim dirtyText, cleanText

dirtyText = ” hello world!!! this is a test… with special@chars# ”
cleanText = CleanAndNormalizeText(dirtyText)

WScript.Echo “原始文本: [” & dirtyText & “]”
WScript.Echo “清理后: [” & cleanText & “]”
End Sub
6. 配置文件解析
Sub ParseConfigFile(configText)
Dim regex, matches, match, i

‘ 匹配 key = value 格式,支持引号和注释
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^\s*(\w+)\s*=\s*(.+?)\s*(?:#.*)?$”
regex.Multiline = True
regex.Global = True

Set matches = regex.Execute(configText)

WScript.Echo “配置项解析:”
For i = 0 To matches.Count – 1
Set match = matches(i)
WScript.Echo ” ” & match.SubMatches(0) & ” = ” & match.SubMatches(1)
Next
End Sub

Sub ConfigParsingDemo()
Dim config
config = “# Database Configuration” & vbCrLf & _
“host = localhost” & vbCrLf & _
“port = 3306” & vbCrLf & _
“username = admin # Admin user” & vbCrLf & _
“password = secret123” & vbCrLf & _
“timeout = 30”

Call ParseConfigFile(config)
End Sub
高级技巧与最佳实践
1. 性能优化技巧
‘ 性能对比:预编译正则表达式
Sub PerformanceComparison()
Dim regex, text, i, startTime, endTime

text = String(10000, “a”) & “b” ‘ 10000个a后跟一个b

‘ 方法1:每次创建新对象(慢)
startTime = Timer
For i = 1 To 1000
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “a+b”
regex.Test text
Next
endTime = Timer
WScript.Echo “每次创建对象: ” & (endTime – startTime) & ” 秒”

‘ 方法2:重用对象(快)
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “a+b”
startTime = Timer
For i = 1 To 1000
regex.Test text
Next
endTime = Timer
WScript.Echo “重用对象: ” & (endTime – startTime) & ” 秒”
End Sub
2. 复杂模式构建技巧
‘ 构建可复用的正则表达式组件
Function BuildRegexPattern(components)
‘ 组件示例: Array(“email”, “phone”, “date”)
Dim patterns, i

patterns = Array( _
“email”, “^\w+@\w+\.\w+$”, _
“phone”, “^\d{3}-\d{3}-\d{4}$”, _
“date”, “^\d{4}-\d{2}-\d{2}$” _
)

BuildRegexPattern = “”
For i = 0 To UBound(components)
Dim j
For j = 0 To UBound(patterns) Step 2
If patterns(j) = components(i) Then
If BuildRegexPattern <> “” Then BuildRegexPattern = BuildRegexPattern & “|”
BuildRegexPattern = BuildRegexPattern & “(” & patterns(j + 1) & “)”
Exit For
End If
Next
Next

If BuildRegexPattern <> “” Then
BuildRegexPattern = “^(” & BuildRegexPattern & “)$”
End If
End Function

Sub ComplexPatternDemo()
Dim pattern, regex, testStrings, str

pattern = BuildRegexPattern(Array(“email”, “phone”))
WScript.Echo “生成的模式: ” & pattern

Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = pattern
regex.IgnoreCase = True

testStrings = Array(“user@example.com”, “123-456-7890”, “invalid”)

For Each str In testStrings
If regex.Test(str) Then
WScript.Echo “✓ ” & str & ” 匹配”
Else
WScript.Echo “✗ ” & str & ” 不匹配”
End If
Next
End Sub
3. 错误处理和调试
Function SafeRegexTest(text, pattern)
Dim regex, result

On Error Resume Next
Set regex = CreateObject(“VBScript.RegExp”)
If Err.Number <> 0 Then
SafeRegexTest = “Error creating RegExp: ” & Err.Description
Exit Function
End If

regex.Pattern = pattern
If Err.Number <> 0 Then
SafeRegexTest = “Error setting pattern: ” & Err.Description
Exit Function
End If

result = regex.Test(text)
If Err.Number <> 0 Then
SafeRegexTest = “Error executing test: ” & Err.Description
Exit Function
End If

On Error GoTo 0
SafeRegexTest = result
End Function

Sub DebugRegex(text, pattern)
Dim regex, matches, match, i

WScript.Echo “=== 正则表达式调试 ===”
WScript.Echo “文本: ” & text
WScript.Echo “模式: ” & pattern

Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = pattern
regex.Global = True

If regex.Test(text) Then
WScript.Echo “✓ 匹配成功”
Set matches = regex.Execute(text)
For i = 0 To matches.Count – 1
Set match = matches(i)
WScript.Echo ” 匹配 ” & (i + 1) & “: ” & match.Value & _
” (位置: ” & match.FirstIndex & “, 长度: ” & match.Length & “)”
If match.SubMatches.Count > 0 Then
Dim j
For j = 0 To match.SubMatches.Count – 1
WScript.Echo ” 捕获组 ” & (j + 1) & “: ” & match.SubMatches(j)
Next
End If
Next
Else
WScript.Echo “✗ 无匹配”
End If
End Sub
4. 实用工具函数库
‘ 实用正则表达式函数库

‘ 验证函数
Function IsValidURL(url)
Dim regex
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^(https?|ftp)://[^\s/$.?#].[^\s]*$”
regex.IgnoreCase = True
IsValidURL = regex.Test(url)
End Function

Function IsValidIPv4(ip)
Dim regex
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$”
IsValidIPv4 = regex.Test(ip)
End Function

Function IsValidHexColor(color)
Dim regex
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$”
IsValidHexColor = regex.Test(color)
End Function

‘ 提取函数
Function ExtractEmails(text)
Dim regex, matches, match, i, emails

Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b”
regex.Global = True
regex.IgnoreCase = True

Set matches = regex.Execute(text)
ReDim emails(matches.Count – 1)

For i = 0 To matches.Count – 1
emails(i) = matches(i).Value
Next

ExtractEmails = emails
End Function

Function ExtractNumbers(text)
Dim regex, matches, match, i, numbers

Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “\d+”
regex.Global = True

Set matches = regex.Execute(text)
ReDim numbers(matches.Count – 1)

For i = 0 To matches.Count – 1
numbers(i) = CLng(matches(i).Value)
Next

ExtractNumbers = numbers
End Function

‘ 替换函数
Function MaskSensitiveData(text)
Dim regex

Set regex = CreateObject(“VBScript.RegExp”)
regex.Global = True

‘ 隐藏信用卡号(保留最后4位)
regex.Pattern = “\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b”
text = regex.Replace(text, “****-****-****-$1”)

‘ 隐藏邮箱
regex.Pattern = “(\w)[\w.-]*@([\w.-]+\.\w+)”
text = regex.Replace(text, “$1***@$2”)

‘ 隐藏电话号码
regex.Pattern = “(\d{3})[\s-]?(\d{3})[\s-]?(\d{4})”
text = regex.Replace(text, “($1) ***-****”)

MaskSensitiveData = text
End Function

Sub UtilityFunctionsDemo()
WScript.Echo “=== 实用函数演示 ===”

‘ 验证
WScript.Echo “URL验证: ” & IsValidURL(“https://www.example.com”)
WScript.Echo “IPv4验证: ” & IsValidIPv4(“192.168.1.1”)
WScript.Echo “颜色验证: ” & IsValidHexColor(“#FF5733”)

‘ 提取
Dim text, emails, numbers
text = “联系邮箱: user@example.com 或 admin@domain.org, 电话: 123-456-7890”
emails = ExtractEmails(text)
numbers = ExtractNumbers(text)
WScript.Echo “提取邮箱: ” & Join(emails, “, “)
WScript.Echo “提取数字: ” & Join(numbers, “, “)

‘ 替换
Dim sensitiveText
sensitiveText = “信用卡: 1234-5678-9012-3456, 邮箱: john.doe@email.com”
WScript.Echo “数据掩码: ” & MaskSensitiveData(sensitiveText)
End Sub
常见问题与解决方案
1. 贪婪 vs 非贪婪匹配
Sub GreedyVsLazyDemo()
Dim regex, text, matches, match

text = “

content1
content2

”

‘ 贪婪匹配(默认)
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “

.*

”
regex.Global = False
Set matches = regex.Execute(text)
WScript.Echo “贪婪匹配: ” & matches(0).Value ‘ 匹配整个字符串

‘ 非贪婪匹配
regex.Pattern = “

.*?

”
regex.Global = True
Set matches = regex.Execute(text)
WScript.Echo “非贪婪匹配:”
For Each match In matches
WScript.Echo ” ” & match.Value
Next
End Sub
2. 多行模式的使用
Sub MultilineDemo()
Dim regex, text, matches

text = “Line 1: Start” & vbCrLf & “Line 2: Middle” & vbCrLf & “Line 3: End”

‘ 单行模式(默认)
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^Line 1”
regex.Multiline = False
WScript.Echo “单行模式 ^Line 1: ” & regex.Test(text)

‘ 多行模式
regex.Multiline = True
WScript.Echo “多行模式 ^Line 1: ” & regex.Test(text)
WScript.Echo “多行模式 ^Line 2: ” & regex.Test(text)
End Sub
3. 性能陷阱和优化
Sub PerformanceTips()
Dim regex, text, i, startTime, endTime

‘ 避免在循环中创建正则表达式对象
text = “The quick brown fox jumps over the lazy dog”

‘ 坏的做法
startTime = Timer
For i = 1 To 10000
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “\b\w{4}\b”
regex.Test text
Next
endTime = Timer
WScript.Echo “循环内创建: ” & FormatNumber(endTime – startTime, 4) & ” 秒”

‘ 好的做法
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “\b\w{4}\b”
startTime = Timer
For i = 1 To 10000
regex.Test text
Next
endTime = Timer
WScript.Echo “重用对象: ” & FormatNumber(endTime – startTime, 4) & ” 秒”

‘ 使用最具体的模式开头
WScript.Echo vbCrLf & “模式优化建议:”
WScript.Echo ” 避免: .*user.* (太宽泛)”
WScript.Echo ” 推荐: \buser\b (更具体)”
End Sub
4. 调试技巧
Sub RegexDebuggingTips()
WScript.Echo “=== 正则表达式调试技巧 ===”
WScript.Echo “1. 从简单开始:逐步构建复杂模式”
WScript.Echo “2. 使用在线工具测试(如 regex101.com)”
WScript.Echo “3. 添加注释:在代码中解释复杂模式”
WScript.Echo “4. 测试边界情况:空字符串、特殊字符”
WScript.Echo “5. 使用 DebugRegex 函数(见上文)”
WScript.Echo “6. 注意转义:特殊字符需要 \ 转义”
WScript.Echo “7. 性能考虑:避免回溯过多的模式”
End Sub
综合实战案例
案例1:批量日志分析器
Sub LogAnalyzer()
Dim regex, logContent, matches, match, i
Dim errorCount, warningCount, infoCount

logContent = _
“[2024-01-15 10:30:15] [INFO] Application started” & vbCrLf & _
“[2024-01-15 10:30:20] [ERROR] Database connection failed: timeout” & vbCrLf & _
“[2024-01-15 10:30:25] [WARN] High memory usage: 85%” & vbCrLf & _
“[2024-01-15 10:30:30] [INFO] Retry connection” & vbCrLf & _
“[2024-01-15 10:30:35] [ERROR] Database connection failed: access denied” & vbCrLf & _
“[2024-01-15 10:30:40] [INFO] Application stopped”

Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “\[(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})\]\s+\[(\w+)\]\s+(.+)”
regex.Global = True

Set matches = regex.Execute(logContent)

errorCount = 0
warningCount = 0
infoCount = 0

WScript.Echo “=== 日志分析报告 ===”
WScript.Echo “总记录数: ” & matches.Count

For i = 0 To matches.Count – 1
Set match = matches(i)
Dim level, message
level = match.SubMatches(1)
message = match.SubMatches(2)

Select Case level
Case “ERROR”
errorCount = errorCount + 1
WScript.Echo “[ERROR] ” & message
Case “WARN”
warningCount = warningCount + 1
Case “INFO”
infoCount = infoCount + 1
End Select
Next

WScript.Echo vbCrLf & “统计:”
WScript.Echo ” 错误: ” & errorCount
WScript.Echo ” 警告: ” & warningCount
WScript.Echo ” 信息: ” & infoCount
End Sub
案例2:配置文件验证器
Function ValidateConfigFile(configText, ByRef errors)
Dim regex, lines, lineNum, line, i
Dim isValid

ReDim errors(0)
errors(0) = “”
isValid = True

‘ 按行处理
lines = Split(configText, vbCrLf)

For lineNum = 0 To UBound(lines)
line = Trim(lines(lineNum))

‘ 跳过空行和注释
If line = “” Or Left(line, 1) = “#” Then
Continue For
End If

‘ 验证 key = value 格式
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “^\s*\w+\s*=\s*.+$”

If Not regex.Test(line) Then
isValid = False
errors(UBound(errors)) = “行 ” & (lineNum + 1) & “: 格式无效 – ” & line
ReDim Preserve errors(UBound(errors) + 1)
End If
Next

‘ 移除最后一个空元素
If UBound(errors) > 0 Then
ReDim Preserve errors(UBound(errors) – 1)
End If

ValidateConfigFile = isValid
End Function

Sub ConfigValidatorDemo()
Dim config, errors, isValid

config = “# Database config” & vbCrLf & _
“host = localhost” & vbCrLf & _
“port = 3306” & vbCrLf & _
“invalid line” & vbCrLf & _
“user = admin” & vbCrLf & _
“pass=secret”

isValid = ValidateConfigFile(config, errors)

WScript.Echo “配置文件验证: ” & IIf(isValid, “通过”, “失败”)
If Not isValid Then
WScript.Echo “错误列表:”
For Each err In errors
WScript.Echo ” ” & err
Next
End If
End Sub
案例3:数据提取和转换工具
Sub DataExtractionTool()
Dim regex, sourceData, results, i

sourceData = _
“Product: Laptop, Price: $999.99, SKU: LPT-001” & vbCrLf & _
“Product: Mouse, Price: $29.99, SKU: MSE-002” & vbCrLf & _
“Product: Keyboard, Price: $79.99, SKU: KBD-003” & vbCrLf & _
“Invalid line here” & vbCrLf & _
“Product: Monitor, Price: $299.99, SKU: MON-004”

‘ 提取产品信息
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “Product:\s*(.+?),\s*Price:\s*\$(\d+\.\d{2}),\s*SKU:\s*(.+)”
regex.Global = True

Dim matches, match
Set matches = regex.Execute(sourceData)

WScript.Echo “=== 产品数据提取 ===”
WScript.Echo “找到 ” & matches.Count & ” 个产品”
WScript.Echo String(60, “-“)

For i = 0 To matches.Count – 1
Set match = matches(i)
WScript.Echo “产品: ” & match.SubMatches(0)
WScript.Echo “价格: $” & match.SubMatches(1)
WScript.Echo “SKU: ” & match.SubMatches(2)
WScript.Echo String(30, “.”)
Next

‘ 转换为CSV
WScript.Echo vbCrLf & “转换为CSV格式:”
WScript.Echo “Product,Price,SKU”
For i = 0 To matches.Count – 1
Set match = matches(i)
WScript.Echo match.SubMatches(0) & “,” & match.SubMatches(1) & “,” & match.SubMatches(2)
Next
End Sub
案例4:代码审查工具
Sub CodeReviewTool(code)
Dim regex, issues, i

issues = Array()

‘ 检查未使用的变量
Set regex = CreateObject(“VBScript.RegExp”)
regex.Pattern = “Dim\s+(\w+).*’ Unused”
regex.Global = True
regex.Multiline = True

If regex.Test(code) Then
Dim matches, match
Set matches = regex.Execute(code)
For i = 0 To matches.Count – 1
ReDim Preserve issues(UBound(issues) + 1)
issues(UBound(issues)) = “未使用的变量: ” & matches(i).SubMatches(0)
Next
End If

‘ 检查过长的行
regex.Pattern = “^.{121,}$”
Set matches = regex.Execute(code)
For i = 0 To matches.Count – 1
ReDim Preserve issues(UBound(issues) + 1)
issues(UBound(issues)) = “行过长 (>” & Len(matches(i).Value) & “字符)”
Next

‘ 检查TODO注释
regex.Pattern = “‘\s*TODO\b”
Set matches = regex.Execute(code)
For i = 0 To matches.Count – 1
ReDim Preserve issues(UBound(issues) + 1)
issues(UBound(issues)) = “TODO注释需要处理”
Next

WScript.Echo “=== 代码审查报告 ===”
If UBound(issues) < 0 Then WScript.Echo "未发现问题" Else For Each issue In issues WScript.Echo "⚠ " & issue Next End If End Sub Sub CodeReviewDemo() Dim code code = "Dim unusedVar ' Unused" & vbCrLf & _ "Dim veryLongVariableNameThatExceedsTheMaximumLineLengthLimit = 123" & vbCrLf & _ "' TODO: Implement this function" & vbCrLf & _ "Dim usedVar" & vbCrLf & _ "usedVar = 1" Call CodeReviewTool(code) End Sub 总结 通过本文的学习,你应该已经掌握了VBScript正则表达式的核心知识和实战技巧。让我们回顾一下关键要点: 核心知识点 基础语法 :元字符、字符类、量词、分组、边界匹配 RegExp对象 :Test、Execute、Replace、Split四大方法 实战应用 :验证、提取、替换、分割、解析 高级技巧 :性能优化、复杂模式构建、错误处理 最佳实践 重用对象 :避免在循环中重复创建RegExp对象 具体模式 :使用最具体的模式开头,减少回溯 测试边界 :始终测试空字符串、特殊字符等边界情况 注释说明 :为复杂模式添加注释,便于维护 错误处理 :使用On Error Resume Next处理潜在错误 学习建议 从简单开始 :先掌握基础语法,再学习复杂模式 多练习 :使用在线工具(如regex101.com)测试模式 阅读文档 :参考VBScript和正则表达式官方文档 实际应用 :在真实项目中应用所学知识 持续优化 :关注性能,不断改进代码 扩展学习 学习其他语言的正则表达式(Python、JavaScript等) 了解正则表达式引擎的工作原理 探索更高级的特性(如零宽断言、递归模式等) 研究正则表达式在不同场景下的最佳实践 现在,你已经具备了使用VBScript正则表达式解决各种文本处理难题的能力。开始实践吧,你会发现正则表达式是处理文本的超级武器!