Michael Yaworski
Michael Yaworski

Reputation: 13483

How can I split a String by all whitespace or commas

Dim nSet As String() = "1   3, 5,6".Split(",| ")

The array would then be:

1   3
5
6

I looked at this example and tried to implement that regex:

Dim nSet As String() = "1   3, 5,6".Split("\\s*(,|\\s)\\s*")

But the array was just:

1   3, 5,6

Expected Output

I just need an array where each element has a single number, or a single number and any amount of whitespace (because then I can use .Trim on the element).

I want to be able to get the array to be:

1
3
5
6

I'm using Microsoft Visual Basic Studio 2010 Express. I'm not sure what language it specifically uses, but it's different than the C languages in ways.

Upvotes: 0

Views: 2737

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Dim nSet As String() = "1   3, 5,6".Split({" ", ","}, StringSplitOptions.RemoveEmptyEntries)

You could use ParamArray separators() As Char overload, but it would return a lot of empty items:

Dim nSet As String() = "1   3, 5,6".Split(" "c, ","c)

Upvotes: 3

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

Dim separators() As String = {",", " "}
Dim nSet As String() = "1   3, 5,6".Split(separators, 
                                          StringSplitOptions.RemoveEmptyEntries)

Upvotes: 7

Related Questions