求VBA中一简单正则表达式

来源:百度知道 编辑:UC知道 时间:2024/05/13 02:52:43
求匹配中间字符串的正则表达式!

如:abcdef (字符串很复杂,这只是简化举例)

如何利用两边ab,ef;得到中间一段cd

().*(?=ef)

前面小括内该如何写法???或是有其它写法???
'利用正则式提取字符串中的特定字符自定义函数
'要引用microsoft vbscript regular expressions 5.5

Function RegExpTest(patrn, strng)
Dim RegEx, Match, Matches ' 建立变量。
Set RegEx = New RegExp ' 建立正则表达式。
With RegEx
.Pattern = patrn ' 设置模式。
.IgnoreCase = True ' 设置是否区分字符大小写。
.Global = False ' 设置全局可用性。
Set Matches = .Execute(strng) ' 执行搜索。
End With

For Each Match In Matches ' 遍历匹配集合。
'RetStr = RetStr & "Match found at position "
'RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
'RetStr = RetStr & Match.Value & "'." & vbCrLf
retstr = Match.Value
Next

VB 不支持后瞻,所以只能用分组实现.直接分组替换

Dim ResultString As String
Dim myRegExp As RegExp
Set myRegExp = New RegExp
myRegExp.Global = True
myRegExp.Pattern = "(?:ab)(.+)(?:(?:ef))"
ResultString = myRegExp.Replace(SubjectString, "$1")

(?<=ab).+(?=ef)
即可
用+替代掉*就去除了abef这样连用而中间没内容的部分

我找到原因了,查MSDN发现VBScript的正则太简单了,不支持标准正则的位置锚定的(?<)和(?=)
因此改成
ab.+ef
这样会返回abcdef,好在ab和ef都是确定的,从结果中去掉就可以了,可以用replace,也可以直接用instr之类的函数。