VBA 使用正则表达式拆分字符串

VBA Using Regular Expressions to Split a String

希望有人能够为我正在做的事情提供更好的方法。不幸的是,数据和代码位于客户端系统上,所以我无法共享它们。

我有一个很长的字符串,它以前是一个数据 table,需要再次将值拆分为行和列。系统被严重锁定,所以我只能使用 VBA。我能想到的最好的方法是使用正则表达式来识别列和行。我已经设置了我的正则表达式对象并针对输入字符串执行,具有我需要的所有匹配项,这很好。问题是如果我这样做

re = CreateObject("VBScript.RegExp")
re.pattern = mypattern
re.split(myString)

据我所知,没有办法保留我正在拆分的值。在某些情况下,无论如何我都想在正则表达式字符串的中间拆分。

我认为最有希望的解决方案是

re = CreateObject("VBScript.RegExp")
re.pattern = mypattern
Set matches = re.execute(myString)
for each match in matches:
    'do something with match.firstindex

我考虑过只插入定界符然后使用拆分。不幸的是 VBA 似乎没有办法将字符插入到字符串中使用 firstindex 看起来有点笨拙。

有人对更好的方法有任何想法吗?非常感谢。

您实际上可以将字符插入到字符串中。取决于您对 "clunky" 的定义,但这是一个示例:

ActiveCell.Characters(5, 1).Insert (" | ")

这会在单元格的第五个字符处放置一个“|”。您可能需要使用查找或循环遍历单元格字符来确定某些位置,但我认为这可能会让您顺利进行。

更新字符串编辑 这只是我的偏好,但编辑字符串似乎不太笨重。您可以使用此设置来获得您想要的东西:

Sub StringSlicerSample()
Dim teststring As String, Separater As String, tangoTxt As String, BeforeTXT As String, AfterTxt As String, MidTxt As String
Dim Position_To_Slice As Integer

teststring = "xxxbangyyy"    
Separater = " | " 'can be whatever you want as separator    
tangoTxt = "bang" 'text to look for that you want use for split
Position_To_Slice = 1 'If you want to split somewhere in between, lets say after the "b"
'put =1 as that's the first position in "bang"

'Insert separator before
BeforeTXT = Mid(teststring, 1, InStr(1, teststring, tangoTxt) - 1) & Separater & Mid(teststring, InStr(1, teststring, tangoTxt), Len(teststring))

'Insert after
AfterTxt = Mid(teststring, 1, InStr(1, teststring, tangoTxt) + Len(tangoTxt) - 1) & Separater & Mid(teststring, InStr(1, teststring, tangoTxt) + Len(tangoTxt), Len(teststring))

'Split inbetween based on position to slice
MidTxt = Mid(teststring, 1, InStr(1, teststring, tangoTxt) + Position_To_Slice - 1) & Separater & Mid(teststring, InStr(1, teststring, tangoTxt) + Position_To_Slice, Len(teststring))


MsgBox BeforeTXT, Title:="Before Example"
MsgBox AfterTxt, Title:="After Example"
MsgBox MidTxt, Title:="Sliced in position " & Position_To_Slice

End Sub