Regex Access中的正则表达式VBA-在两个字符串之间查找文本
我在Access VBA中遇到了一个正则表达式问题,玩得很开心 我的目标是从链接的数据库连接字符串中提取服务器。基本上,连接字符串如下所示 ODBC;驱动程序=SQL Server;SERVER=compName\sqlexpress;可信连接=是;APP=微软Office 2010;数据库=数据库名称 我可以让第一个正则表达式工作,但它正在返回 服务器=compName\sqlexpress 我只想把这个还给你 compName\sqlexpressRegex Access中的正则表达式VBA-在两个字符串之间查找文本,regex,ms-access,vba,ms-access-2010,Regex,Ms Access,Vba,Ms Access 2010,我在Access VBA中遇到了一个正则表达式问题,玩得很开心 我的目标是从链接的数据库连接字符串中提取服务器。基本上,连接字符串如下所示 ODBC;驱动程序=SQL Server;SERVER=compName\sqlexpress;可信连接=是;APP=微软Office 2010;数据库=数据库名称 我可以让第一个正则表达式工作,但它正在返回 服务器=compName\sqlexpress 我只想把这个还给你 compName\sqlexpress 我的理解是,?下面是使用RegEx的解决方
我的理解是,
?下面是使用RegEx的解决方案(可以转换为函数的完整代码):
您的函数更改如下(我在模式中添加了应返回的附加参数设置部分):
不确定为什么不能使用?
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
Sub qTest_3()
Dim objRE As New RegExp
Dim Tekst As String
Dim Wynik As Variant
Tekst = "ODBC;DRIVER=SQL Server;SERVER=compName\sqlexpress;Trusted_Connection=Yes;APP=Microsoft Office 2010;DATABASE=databaseName"
With objRE
.Global = True
.IgnoreCase = True
.Pattern = "(^.*;SERVER=)(.*)(;Trusted.*)"
Wynik = .Replace(Tekst, "$2") 'only 2nd part of the pattern will be returned
End With
Debug.Print Wynik
End Sub
Public Function RxMatchReturn( _
ByVal SourceString As String, _
ByVal Pattern As String, _
StringPart As Byte, _
Optional ByVal IgnoreCase As Boolean = True, _
Optional ByVal MultiLine As Boolean = True) As Variant
'Microsoft VBScript Regular Expressions 5.5
On Error GoTo errHandler
Dim oMatches As MatchCollection
With New RegExp
.MultiLine = MultiLine
.IgnoreCase = IgnoreCase
.Global = True
.Pattern = Pattern
RxMatchReturn = .Replace(SourceString, "$" & StringPart)
End With
errHandler:
Debug.Print err.Description
End Function