编辑:哇,感谢这么多的建议,但我想要一个正则表达式解决方案,专门用于未来更复杂的使用。
我需要在 VBA Excel 中拆分文本字符串的支持。我环顾四周,但解决方案要么适用于其他语言,要么无法使其在 VBA 中工作。
我只想用单斜杠分割单词:
text1/text2- split
text1//text2- no split
text1/text2//text3 - split after text1
Run Code Online (Sandbox Code Playgroud)
我尝试使用 regexp.split 函数,但认为它在 VBA 中不起作用。当谈到模式时,我的想法如下:
(?i)(?:(?<!\/)\/(?!\/))
Run Code Online (Sandbox Code Playgroud)
但在我的宏中执行搜索时,当它在以下网站上运行时,我也会收到错误: https: //www.myregextester.com/index.php#sourcetab
您可以使用正则表达式匹配方法而不是拆分方法。您需要匹配除/或 double之外的任何字符//才能获取所需的值。
这是正则表达式的“包装”(即带有交替)版本:
(?:[^/]|//)+
Run Code Online (Sandbox Code Playgroud)
这是一个演示
这是一个更高效但可读性较差的:
[^/]+(?://[^/]*)*
Run Code Online (Sandbox Code Playgroud)
查看另一个演示
这是一个有效的 VBA 代码:
Sub GetMatches(ByRef str As String, ByRef coll As collection)
Dim rExp As Object, rMatch As Object
Set rExp = CreateObject("vbscript.regexp")
With rExp
.Global = True
.pattern = "(?:[^/]|//)+"
End With
Set rMatch = rExp.Execute(str)
If rMatch.Count > 0 Then
For Each r_item In rMatch
coll.Add r_item.Value
Debug.Print r_item.Value
Next r_item
End If
Debug.Print ""
End Sub
Run Code Online (Sandbox Code Playgroud)
调用子程序如下:
Dim matches As New collection
Set matches = New collection
GetMatches str:="text1/text2", coll:=matches
Run Code Online (Sandbox Code Playgroud)
以下是上述 3 个字符串的结果:
1. text1/text2
text1
text2
2. text1/text2//text3
text1
text2//text3
3. text1//text2
text1//text2
Run Code Online (Sandbox Code Playgroud)