Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string based on regexp

Tags:

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

like image 252
Anand Shah Avatar asked Mar 30 '09 07:03

Anand Shah


People also ask

Can you use regex to split a string?

You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.

Is regex faster than string split?

Regex will work faster in execution, however Regex's compile time and setup time will be more in instance creation. But if you keep your regex object ready in the beginning, reusing same regex to do split will be faster. String.

How do you split a string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

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");
like image 78
Andy White Avatar answered Oct 11 '22 09:10

Andy White