views:

371

answers:

2

Hi, I want to split a string in C# that looks like

a : b : "c:d"

so that the resultant array will have

Array[0] = "a"

Array[1] = "b"

Array[2] = "c:d"

what regexp do I use to achieve the required result.

Many Thanks

+1  A: 

This seems to work in RegexBuddy for me

(\w+)\s:\s(\w+)\s:\s"(\w+:\w+)"

input

a : b : "c:d"

matched groups

  1. a
  2. b
  3. c:d

As always be careful and understand what the regex actually does. Don't just copy blindly. This matches word characters \w, spaces \s, etc. Consider what data your input will actually have in it!

Jeff Atwood
Great, now he has *two* problems ;p
Neil Barnwell
I got 99 problems but a regex ain't one.
Jeff Atwood
I think there should be more wide solution with |..smth like:(\w+)\s:|:\s"(\w+:\w+)" ..or kind of this
nihi_l_ist
+1  A: 

If the delimiter colon is separated by whitespace, you can use \s to match the whitespace:

string example = "a : b : \"c:d\"";
string[] splits = Regex.Split(example, @"\s:\s");
Andy White
Whoops, I guess this split will keep the quotes around "c:d"...
Andy White
Thanks Andy, that helps a great deal.
Anand