Reputation: 13
I'd like to get a String array from a String that is delimited with spaces (" ") and commas. Is there a clever way to do this?
For example, if the string was:
cat dog giraffe "big elephant" snake
I'd like the resulting array to contain strings
cat
dog
giraffe
big elephant
snake
I know I could do a Split(str, " ") but the result would differ from what I wanted. I've never used RegEx, but I have a hunch that the solution might have something to do with it.
Upvotes: 1
Views: 1254
Reputation: 5049
You can use a regex for this :
Const data = "åäöÄ åäöÄ ""åäöÄ åäöÄ"" åäöÄ"
Dim matches = Regex.Matches (data, "\p{L}+|""\p{L}+(?: \p{L}+)*""")
For Each m As Match in matches
Console.WriteLine (m.Value.Trim(""""))
Next
The regex works as follow :
Then we just have to Trim
the resulting match to eliminate the potential startind/ending quote
Note : see here for more info about \p{L}
Upvotes: 0
Reputation: 626689
Treating the input as space-delimited CSV can greatly simplify the task:
Imports Microsoft.VisualBasic.FileIO.TextFieldParser
...
Dim s As String = "cat dog giraffe ""big elephant"" snake"
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(New System.IO.StringReader(s))
Dim CurrentRecord As String()
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {" "}
afile.HasFieldsEnclosedInQuotes = True
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
Console.WriteLine(String.Join("; ", CurrentRecord))
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
It prints cat; dog; giraffe; big elephant; snake
.
The code is adapted from Parse Delimited CSV in .NET.
Upvotes: 3