所以,VBScript apparently doesn't support Lookbehind at all.
我正在寻找可以与VBScript一起使用的替代有效正则表达式。
仅供参考,我将在HP UFT中使用它,所以我别无选择,只能使用VBScript(如果没有其他最简单的方法,我可能需要查看其他选项,例如执行Java(或其他语言)代码来自VBS)。
我想要实现的目标:
从给定的一堆文本中,我想提取某些字母数字字符串。此字符串可能包含-
,_
,.
,/
,//
等。
只有我知道的是,此字符串后面会跟一个特定的单词(例如 DIA ),并且此字符串后面会有一个空格。
这里我可以使用VBS代码片段作为替代方案:
此示例代码仅检索第一个匹配项。如果我找不到其他选择,我可以修改它。
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
。
答案 0 :(得分:5)
您可以将正则表达式重新添加到capturing group的模式中,以便您只访问所需的值:
DIA\s+(\S+)
请参阅regex demo。
请注意,您甚至不需要前瞻,因为.*?(?=\s)
与除了换行符之外的任何0+字符匹配尽可能少的空格。当然,如果您需要检查空格,只需在模式的末尾添加\s
。
模式详情
DIA
- 一个DIA
子字符串(前缀为\b
word boundary,如果您需要一个完整的单词匹配)\s+
- 一个或多个空格(\S+)
- 第1组:除空白字符之外的一个或多个字符。这是一个VBA测试:
Sub GetValues()
Dim rExp As Object, allMatches As Object, match As Object
Dim s As String
s = "DIA 8778680044 SVU-RMW ANNISTON SERF1450 COMMERCE BLVD ANNISTONAL DIA DS1IT-15600804-123 SVU-RMW ANNISTON2130 ROBERTS DR ANNISTONAL"
Set rExp = CreateObject("vbscript.regexp")
With rExp
.Global = True
.MultiLine = False
.Pattern = "DIA\s+(\S+)"
End With
Set allMatches = rExp.Execute(s)
For Each match In allMatches
WScript.Echo match.SubMatches.Item(0)
Next
End Sub
输出:
8778680044
DS1IT-15600804-123