M M
M M

Reputation: 187

How do you use Split() on a hyphen?

I have a string that contains "-" near the end. I want to return everything to the left of that hyphen.

I don't know how to use Split() or Regex() to do that.

Upvotes: 2

Views: 2973

Answers (3)

xanadont
xanadont

Reputation: 7604

Use a combo of Instr(), Mid() and Len() here

Upvotes: 1

brettdj
brettdj

Reputation: 55682

Two methods that handle removing the hyphen and a non-hyphen case

Sub Test1()
    Dim StrTest As String
    StrTest = "I have a hypen-somewhere"
    If InStr(StrTest, "-") > 0 Then
        MsgBox Left$(StrTest, InStr(StrTest, "-") - 1)
    Else
        MsgBox "Not found"
    End If
End Sub

Sub Test2()
    Dim StrTest As String
    Dim vString
    StrTest = "I have a hypen-somewhere"
    vString = Split(StrTest, "-")
    If UBound(vString) > 0 Then
        MsgBox vString(0)
    Else
        MsgBox "Not found"
    End If
End Sub

Upvotes: 6

Jason Larke
Jason Larke

Reputation: 5609

You could try something like:

Dim hyphenString As String = "hello-world"
Dim leftSide As String = Left(hyphenString, InStr(hyphenString, "-"))

leftSide should now contain "hello"

Upvotes: 1

Related Questions