tags:

views:

73

answers:

2

I'm using the code below to take a string and split it up into an array. It will take: Disney Land and make it two separate elements. If the string contains "Disney Land" then it is one element in the array. Works great, however it adds some empty elements to the array each time. So I just iterate over the elements and remove them if they are empty. Is there a tweak to the code below that will prevent those empty elements from occurring?

Private m_Reg As Regex
m_Reg = New Regex("([^""^\s]+)\s*|""([^""]+)""\s*")
Dim rezsplit = m_Reg.Split(criteria)
+2  A: 

Use Matches instead of Split and you won't have to worry about that. You can simplify the regex, too:

m_Reg = New Regex("""([^""]+)""|[^""\s]+")

EDIT: I forgot to deal with the problem of scraping off the quotes. This will make it easier:

m_Reg = New Regex("""(?<Value>[^""]+)""|(?<Value>[^""\s]+)")

Now, whichever alternative matches, the desired text can be found in the group named "Value".

Alan Moore
I was trying it out but it returns a matches collection. I need a String(). I tried ctype, and then tried the copyto method. I'm not sure how I can make it a string without iterating the collection. I'm already iterating the collection to get rid of empty strings so I was hoping to avoid that.
Cj Anderson
I'm not fluent in .NET, but I'd be very surprised if there isn't a way to decorate a MatchCollection as a String array. Linq, maybe?
Alan Moore
+1 from me. I posted the .NET approach.
Ahmad Mageed
+1  A: 

Alan's answer is correct. Using his pattern we could use LINQ to filter the Split results or we could use Matches as he suggested.

Dim input As String = "Islands of Adventure ""Disney Land"" Universal Studios"
Dim pattern As String = "(?<Value>[^""\s]+)|""(?<Value>[^""]+)"""
Dim result = Regex.Split(input, pattern).Where(Function(s) s.Trim <> "")

Console.WriteLine("Split Result:")
For Each s In result
    Console.WriteLine(s)
Next

Console.WriteLine("Matches:")
For Each m As Match In Regex.Matches(input, pattern)
    Console.WriteLine(m.Groups("Value").Value)
Next

''# to get string arrays use either of these instead
Dim splitArray As String() = Regex.Split(input, pattern) _
                              .Where(Function(s) s.Trim <> "") _
                              .ToArray()
Dim matchArray As String() = Regex.Matches(input, pattern).Cast(Of Match) _
                                  .Select(Function(m) m.Groups("Value").Value) _
                                  .ToArray()
Ahmad Mageed
Works great thank you.
Cj Anderson
@Cj glad that helped :)
Ahmad Mageed