我想按照正则表达式将字符串分割成数组,类似于PHP中的preg_split或VBScript中的Split函数,但是使用正则表达式作为定界符。
使用VBScript Regexp对象,我可以执行一个正则表达式,但它返回匹配项(所以我得到了我的分隔符的集合...这不是我想要的)
有没有办法实现这个功能?
谢谢
我想按照正则表达式将字符串分割成数组,类似于PHP中的preg_split或VBScript中的Split函数,但是使用正则表达式作为定界符。
使用VBScript Regexp对象,我可以执行一个正则表达式,但它返回匹配项(所以我得到了我的分隔符的集合...这不是我想要的)
有没有办法实现这个功能?
谢谢
"#@#"
),那么您可以使用正则表达式替换将您的模式的所有匹配项替换为"#@#"
,然后在"#@#"
上进行拆分。\d+
,那么您搜索(.*?)\d+
,然后提取每个匹配中组捕获的内容(在rubular.com上查看前和后)。我认为你可以通过使用Execute来匹配所需的分隔符字符串,但是将所有前面的字符(在上一个匹配之后)捕获为一组。以下是一些可以实现你想要的功能的代码。
'// Function splits a string on matches
'// against a given string
Function SplitText(strInput,sFind)
Dim ArrOut()
'// Don't do anything if no string to be found
If len(sFind) = 0 then
redim ArrOut(0)
ArrOut(0) = strInput
SplitText = ArrOut
Exit Function
end If
'// Define regexp
Dim re
Set re = New RegExp
'// Pattern to be found - i.e. the given
'// match or the end of the string, preceded
'// by any number of characters
re.Pattern="(.*?)(?:" & sFind & "|$)"
re.IgnoreCase = True
re.Global = True
'// find all the matches >> match collection
Dim oMatches: Set oMatches = re.Execute( strInput )
'// Prepare to process
Dim oMatch
Dim ix
Dim iMax
'// Initialize the output array
iMax = oMatches.Count - 1
redim arrOut( iMax)
'// Process each match
For ix = 0 to iMax
'// get the match
Set oMatch = oMatches(ix)
'// Get the captured string that precedes the match
arrOut( ix ) = oMatch.SubMatches(0)
Next
Set re = nothing
'// Check if the last entry was empty - this
'// removes one entry if the string ended on a match
if arrOut(iMax) = "" then Redim Preserve ArrOut(iMax-1)
'// Return the processed output
SplitText = arrOut
End Function
\n
的数组可能行不通。看起来它只会寻找字符串\n
而不是寻找换行符,对吗? - Michael Innes我写这个是为了自己使用。也许正是你所需要的。
Function RegSplit(szPattern, szStr)
Dim oAl, oRe, oMatches
Set oRe = New RegExp
oRe.Pattern = "^(.*)(" & szPattern & ")(.*)$"
oRe.IgnoreCase = True
oRe.Global = True
Set oAl = CreateObject("System.Collections.ArrayList")
Do
Set oMatches = oRe.Execute(szStr)
If oMatches.Count > 0 Then
oAl.Add oMatches(0).SubMatches(2)
szStr = oMatches(0).SubMatches(0)
Else
oAl.Add szStr
Exit Do
End If
Loop
oAl.Reverse
RegSplit = oAl.ToArray
End Function
'**************************************************************
Dim A
A = RegSplit("[,|;|#]", "bob,;joe;tony#bill")
WScript.Echo Join(A, vbCrLf)
Returns:
bob
joe
tony
bill
\s+
。 - NetMage