Split string on single forward slashes with RegExp

前端 未结 4 538
夕颜
夕颜 2020-12-19 21:46

edit: wow, thanks for so many suggestions, but I wanted to have a regexp solution specifically for future, more complex use.

I need support with splitting text strin

相关标签:
4条回答
  • 2020-12-19 22:10

    You can use a RegExp match approach rather than split one. You need to match any character other than / or double // to grab the values you need.

    Here is a "wrapped" (i.e. with alternation) version of the regex:

    (?:[^/]|//)+
    

    Here is a demo

    And here is a more efficient, but less readable:

    [^/]+(?://[^/]*)*
    

    See another demo

    Here is a working VBA code:

    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
    

    Call the sub as follows:

    Dim matches As New collection
    Set matches = New collection
    GetMatches str:="text1/text2", coll:=matches
    

    Here are the results for the 3 strings above:

    1. text1/text2
     text1
     text2
    
    2. text1/text2//text3
     text1
     text2//text3
    
    3. text1//text2
     text1//text2
    
    0 讨论(0)
  • 2020-12-19 22:16

    Go to Data tab, then Text to Columns option. Later, choose "Delimited" option and then select "other" and put any delimiter you want.

    0 讨论(0)
  • 2020-12-19 22:24

    Text to columns will work. Another option, if you want to keep the original value, is to use formulas: in B1

    =left(a1,find(":",a1)-1) 
    

    in C1

    =mid(a1,find(":",a1)+1,len(a1))
    
    0 讨论(0)
  • 2020-12-19 22:34
    Public Sub customSplit()
        Dim v As Variant
    
        v = Split("text1/text2//text3", "/")
        v = Replace(Join(v, ","), ",,", "//")
    
        Debug.Print v   '-> "text1,text2//text3"
    End Sub
    

    or

    Replace(Replace("text1/text2//text3", "/", ","), ",,", "//")   '-> "text1,text2//text3"
    
    0 讨论(0)
提交回复
热议问题