在 VBA 中使用条件正则表达式解析文本
Parsing Text with Conditional Regular Expressions in VBA
我正在使用 Microsoft VBScript 正则表达式 5.5 在 Excel 文档的单元格内使用 VBA 中的正则表达式解析大量文本数据。
我不知道如何创建一个正则表达式短语来匹配以下内容:"deploy"、"deploying"、"deployment" 但不是具体说明的内容 "redeploy"。到目前为止,我已经尝试了以下表达式,但无济于事:
(^[rR][eE])([dD][eE][pP][lL][oO][yY])
(^[rR][eE])?([dD][eE][pP][lL][oO][yY])
.(^[rR][eE])([dD][eE][pP][lL][oO][yY])
*(^[rR][eE])([dD][eE][pP][lL][oO][yY])
有人能发现我做错了什么吗?或者考虑到 Regex 的功能,这不可能吗?
试试这个正则表达式:
redeploy\w*|(\w*deploy\w*)
您要查找的词在第一个捕获组中。它将捕获包含 deploy 但不以 redeploy.
开头的每个单词
您也可以尝试下面的代码(未测试):
Dim searchStr As String
searchStr = "redeploy deploying redeployment deploy"
Dim regex As New VBScript_RegExp_55.RegExp
Dim matches
regex.Pattern = "redeploy\w*|(\w*deploy\w*)"
regex.IgnoreCase = True
regex.Global = True
If regex.test(searchStr) Then
Set matches = regex.Execute(searchStr)
Dim match As Variant
For Each match In matches
Debug.Print match.Submatches(0)
Next
End If
使用这个:
>> Set r = New RegExp
>> r.IgnoreCase = True
>> r.Pattern = "\bdeploy"
>> For Each w In Split("redeploy deploy deploywhatever misdeploy")
>> WScript.Echo w, CStr(r.Test(w))
>> Next
>>
redeploy Falsch
deploy Wahr
deploywhatever Wahr
misdeploy Falsch
>>
尝试 "a word starting with 'deploy'" 是否符合您的规格。
"(?!re)\b\S*deploy\S*"
不会匹配重新部署,但会匹配,例如错误部署,以及各种形式(部署、部署等)
如果你能消除所有"prefix"部署的话,那么
"\bdeploy\S*"
会更简单。
我正在使用 Microsoft VBScript 正则表达式 5.5 在 Excel 文档的单元格内使用 VBA 中的正则表达式解析大量文本数据。
我不知道如何创建一个正则表达式短语来匹配以下内容:"deploy"、"deploying"、"deployment" 但不是具体说明的内容 "redeploy"。到目前为止,我已经尝试了以下表达式,但无济于事:
(^[rR][eE])([dD][eE][pP][lL][oO][yY])
(^[rR][eE])?([dD][eE][pP][lL][oO][yY])
.(^[rR][eE])([dD][eE][pP][lL][oO][yY])
*(^[rR][eE])([dD][eE][pP][lL][oO][yY])
有人能发现我做错了什么吗?或者考虑到 Regex 的功能,这不可能吗?
试试这个正则表达式:
redeploy\w*|(\w*deploy\w*)
您要查找的词在第一个捕获组中。它将捕获包含 deploy 但不以 redeploy.
开头的每个单词
您也可以尝试下面的代码(未测试):
Dim searchStr As String
searchStr = "redeploy deploying redeployment deploy"
Dim regex As New VBScript_RegExp_55.RegExp
Dim matches
regex.Pattern = "redeploy\w*|(\w*deploy\w*)"
regex.IgnoreCase = True
regex.Global = True
If regex.test(searchStr) Then
Set matches = regex.Execute(searchStr)
Dim match As Variant
For Each match In matches
Debug.Print match.Submatches(0)
Next
End If
使用这个:
>> Set r = New RegExp
>> r.IgnoreCase = True
>> r.Pattern = "\bdeploy"
>> For Each w In Split("redeploy deploy deploywhatever misdeploy")
>> WScript.Echo w, CStr(r.Test(w))
>> Next
>>
redeploy Falsch
deploy Wahr
deploywhatever Wahr
misdeploy Falsch
>>
尝试 "a word starting with 'deploy'" 是否符合您的规格。
"(?!re)\b\S*deploy\S*"
不会匹配重新部署,但会匹配,例如错误部署,以及各种形式(部署、部署等)
如果你能消除所有"prefix"部署的话,那么
"\bdeploy\S*"
会更简单。