【发布时间】:2014-02-11 09:35:18
【问题描述】:
我在 Access VBA 中遇到了一个 RegEx 问题。
我的目标是从链接的数据库连接字符串中提取服务器。基本上,连接字符串看起来像
ODBC;DRIVER=SQL Server;SERVER=compName\sqlexpress;Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=databaseName
我能够让第一个正则表达式工作,但它正在返回
SERVER=compName\sqlexpress
我希望这个只返回
compName\sqlexpress
我的理解是?<= 运算符应该允许正则表达式正常工作,但我收到以下错误“对象'IRegExp2'的方法'执行'失败。”
对于任何 Microsoft RegEx 语法,我能找到的唯一文档是 here,它不是运行时 5.5 VBScript 库,但我不确定在哪里可以获得支持的语法。
这是我用来测试的代码。我的数据库有很多链接表。
Sub printServerStringInformation()
Dim rxPattern As String
rxPattern = "(?=SERVER)(.*)(?=;Trusted)"
Debug.Print RxMatch(CurrentDb.tableDefs(1).Connect, rxPattern, False)
rxPattern = "(?<=SERVER)(.*)(?=;Trusted)"
Debug.Print RxMatch(CurrentDb.tableDefs(1).Connect, rxPattern, False)
End Sub
这是我正在使用的功能:
Public Function RxMatch( _
ByVal SourceString As String, _
ByVal Pattern As String, _
Optional ByVal IgnoreCase As Boolean = True, _
Optional ByVal MultiLine As Boolean = True) As Variant
'Microsoft VBScript Regular Expressions 5.5
'http://www.zytrax.com/tech/web/regex.htm#more
'http://bytecomb.com/regular-expressions-in-vba/
'http://xkcd.com/1171/
On Error GoTo errHandler
Dim oMatches As MatchCollection
With New RegExp
.MultiLine = MultiLine
.IgnoreCase = IgnoreCase
.Global = False
.Pattern = Pattern
Set oMatches = .Execute(SourceString)
If oMatches.Count > 0 Then
RxMatch = oMatches(0).value
Else
RxMatch = ""
End If
End With
errHandler:
Debug.Print Err.Description
End Function
【问题讨论】:
-
不知道为什么你不能使用
?<=,但如果你使用正则表达式的选择性括号,你应该能够使用"SERVER=(.*?);Trusted"获取信息,然后使用存储在第一个正则表达式变量中的字符串. (类似于oMatches(0).subMatches(0)?)
标签: regex ms-access vba ms-access-2010