有没有办法在VBA正则表达式中做出消极和积极的观察?
如果字符串以“A”开头,我想不匹配,所以我目前在模式的开头做^ A,然后删除match(0)的第一个字符。显然不是最好的方法!
我正在使用regExp对象。
答案 0 :(得分:11)
VBA提供了积极和消极的前瞻,但却不一致而不是后视。
我见过的使用Regex和VBA的最好例子是Patrick Matthews的this article
[使用Execute
而不是Replace
更新了示例
虽然我对你的用法并不完全清楚,你可以使用
这样的功能对于所有不以a开头的单词都会返回第二个字符的所有内容(使用子匹配 - (
中的模式和)
是子匹配1 -
Sub TestString()
MsgBox ReducedText("cfat dcat")
MsgBox ReducedText("Sat all over the hat again")
End Sub
Function ReducedText(strIn As String) As String
Dim objRegex As Object
Dim objRegMC As Object
Dim objRegM As Object
Dim strOut As String
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.IgnoreCase = True
'not needed if matching the whole string
.Global = True
.Pattern = "\b[^a\s]([a-z]+)"
If .test(strIn) Then
Set objRegMC = .Execute(strIn)
For Each objRegM In objRegMC
strOut = strOut & objRegM.submatches(0) & vbNewLine
Next
ReducedText = strOut
Else
ReducedText = "Starts with A"
End If
End With
End Function
答案 1 :(得分:0)
如何将^ A放在非捕获组中并使用Match对象的SubMatches属性来获取匹配值?