c# – split string based on regexp – Education Career Blog

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

a : b : “c:d”

so that the resultant array will have

Array0 = “a”

Array1 = “b”

Array2 = “c:d”

what regexp do I use to achieve the required result.

Many Thanks

,

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");

,

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!

Leave a Comment