【发布时间】:2018-03-22 05:24:45
【问题描述】:
所以,VBScript apparently doesn't support Lookbehind at all.
我正在寻找可以与 VBScript 一起使用的替代有效正则表达式。
仅供参考,我将在 HP UFT 中使用它,所以我别无选择,只能使用 VBScript(如果没有其他最简单的方法,我可能不得不考虑其他选项,例如执行 Java(或其他语言)代码来自 VBS)。
我想要达到的目标:
从给定的一堆文本中,我想提取某些字母数字字符串。该字符串可能包括-、_、.、/、//等。
我只知道,这个字符串后面会跟着一个特定的单词(例如DIA),并且这个字符串后面会有一个空格。
这里是我可以使用的 VBS 代码 sn-p:
此示例代码仅检索第一个匹配项。如果找不到其他选择,我可以修改它。
serviceType = "DIA"
tempTxt = obj.GetROProperty("innertext")
If InStr(1, tempTxt, serviceType, 0) > 0 Then
iStartPoint = InStr(1, tempTxt, serviceType, 0) + Len(serviceType)
End If
tempTxt = LTrim(Mid(tempTxt, iStartPoint))
iStartPoint = InStr(1, tempTxt, " ", 1)
MsgBox Left(tempTxt, iStartPoint)
这是我正在使用的正则表达式:
(?<=DIA\s).*?(?=\s)
这是我尝试并成功工作的demo。 我只需要找到 VBScript 替代方案。
更新
这是我尝试建议的正则表达式后得到的结果:
(返回值看起来不同,因为我使用了不同的输入文本。)
这是我正在使用的代码:
Call RegExpMultiSearch(tempTxt, "DIA\s+(\S+)")
Public RegMatchArray
Function RegExpMultiSearch(targetString, ptrn)
'CREATE THE REGULAR EXPRESSION
Set regEx = New RegExp
regEx.Pattern = ptrn
regEx.IgnoreCase = True 'False
regEx.Global = True
'PERFORM THE SEARCH
Set Matches = regEx.Execute(targetString)
'REPORTING THE MATCHES COLLECTION
If Matches.Count = 0 Then
Actual_Res = "NO occurrence of pattern '" & ptrn & "' found in string '" & targetString & "'"
Print Actual_Res
Else
'ITERATE THROUGH THE MATCHES COLLECTION
For Each Match in Matches
'ADD TO ARRAY
ReDim Preserve arrArray(i)
arrArray(i) = Match.Value
i = i + 1
Next
Actual_Res = UBound(arrArray) - 1 & " occurrence of pattern '" & ptrn & "' found in string '" & targetString & "' successfully"
Print Actual_Res
RegMatchArray = arrArray
End If
If IsObject(regEx) Then Set regEx = Nothing End If
If IsObject(Matches) Then Set Matches = Nothing End If
End Function
最终更新
我通过使用建议的正则表达式得到了想要的结果。我还必须使用 SubMatches(0) 而不是 Match.Value。
【问题讨论】:
-
问题更新后的correct regex is still the same,请看下面我的回答。
-
显示代码。您没有访问 Group1 值(我的 sn-p 中的
match.SubMatches.Item(0))。 -
Match.Value->Match.Submatches(0).Value。您需要获取捕获组的值,而不是完整匹配。 -
我的错。只是
Match.Submatches(0)(或Match.Submatches.Item(0))没有.Value。 -
是的,你是对的,应该没有
.Value