A string separated by two single quotes
I have a bare string where each word is separated by a comma between two single quotes.
Dim str As String = "a','b','c','d','e"
I want to split a string with ','
so that I have an array like this:
["a", "b", "c", "d", "e"]
My code looks like this:
str.Split("','")
The returned array ["a", ",", "b", ",", "c", ",", "d", ",", "e"]
.
I didn't expect this behavior and was looking for an explanation of how the string is split.
source to share
The reason for the unexpected result is the fact that you are passing a string as an argument Split
.
There is no overload Split
that takes a string, since you have the Strict off option, the compiler uses the overload Split(Char)
by taking only the first character in the string. So in your case
String.Split("','")
coincides with
String.Split("'")
You want to toggle the Strict On option so your code won't compile (this is good, because it avoids such errors).
To achieve what you want, you must pass an array of strings to the method (in this case, an array containing only one string):
Dim input As String = "a','b','c','d','e"
Dim splitChars() As String = {"','"}
Dim output As String() = input.Split(splitChars, StringSplitOptions.None)
source to share
You don't need regex, you can use Split(","c)
and remove everything '
with String.Trim
:
Dim result = str.Split(","c).Select(Function(s) s.Trim("'"c)).ToArray()
Result: a,b,c,d,e
Side note: from Option Strict
to Off
Split("','")
is only delimited by the first character, not the whole substring. If you want you to have to use overloading String.Split
.
For example (note which {"','"}
is string()
):
str.Split({"','"}, StringSplitOptions.None)
C Option Strict On
that wouldn't even compile, which is good because there is no overload. Therefore, I recommend to install Option Strict
in On
default. You will learn a lot about the structure and types of .NET by fixing compiler errors. You will also learn how to write more robust code this way.
source to share
You can do it without regex. Try the following:
Dim str As String = "a','b','c','d','e" 'note that ',c was changed to ','c
Dim seperator() As String = New String() {"','"}
Dim result() As String = str.Split(seperator, StringSplitOptions.RemoveEmptyEntries)
I tried it using C # with this code:
string source = "a','b','c','d','e";
var seperator = new string[] {"','"};
var result = source.Split(seperator, StringSplitOptions.RemoveEmptyEntries);
and then converted via http://www.developerfusion.com/tools/convert/csharp-to-vb/ , so the vb.net syntax can be sketchy.
Result:
source to share
Its performance, try it ...
Note: Imports System.Text.RegularExpressions
Public Shared Function SplitStr(ByVal List As String) As String
Dim col As MatchCollection = Regex.Matches(List, "'(.*?)'")
Dim newList As String = ""
For Each m As Match In col
Dim g As Group = m.Groups(1)
If newList = "" Then
newList = g.Value
Else
newList += "," & g.Value
End If
Next
Return newList
End Function
source to share