分割string正向斜线与RegExp
编辑:哇,感谢这么多的build议,但我想有一个专门为未来,更复杂的使用正则expression式解决scheme。
我需要在VBA Excel中分割文本string的支持。 我环顾四周,但解决scheme要么是其他语言,要么我不能使它在VBA中工作。
我只想用单斜杠分割单词:
text1/text2- split text1//text2- no split text1/text2//text3 - split after text1
我尝试使用regexp.split函数,但不认为它在VBA中的作品。 当涉及到模式我想像下面的东西:
(?i)(?:(?<!\/)\/(?!\/))
但是当我在macros中执行search时,它也会出错,同时它在如下网站上工作: https : //www.myregextester.com/index.php#sourcetab
您可以使用RegExp匹配方法而不是分割方法。 您需要匹配除/
或双/
以外的任何字符以获取所需的值。
这里是正则expression式的“包装”(即交替)版本:
(?:[^/]|//)+
这里是一个演示
这里是一个更有效的,但不太可读的:
[^/]+(?://[^/]*)*
看另一个演示
这是一个可用的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
调用子如下:
Dim matches As New collection Set matches = New collection GetMatches str:="text1/text2", coll:=matches
以下是上面3个string的结果:
1. text1/text2 text1 text2 2. text1/text2//text3 text1 text2//text3 3. text1//text2 text1//text2
Public Sub customSplit() Dim v As Variant v = Split("text1/text2//text3", "/") v = Replace(Join(v, ","), ",,", "//") Debug.Print v '-> "text1,text2//text3" End Sub
要么
Replace(Replace("text1/text2//text3", "/", ","), ",,", "//") '-> "text1,text2//text3"
转到“数据”选项卡,然后select“文本到列”选项。 稍后,select“分隔”选项,然后select“其他”,并把你想要的任何分隔符。
文本到列将工作。 另一个select,如果你想保持原来的价值,是使用公式:在B1
=left(a1,find(":",a1)-1)
在C1
=mid(a1,find(":",a1)+1,len(a1))