ingh.am
ingh.am

Reputation: 26742

Writing a regex command to split an array in c#

Regex is one of those things I've wanted to be able to write myself and although I have a basic understand of how it works I've never found myself in the situation where I needed to use it where it doesn't exist already widely on the web (such as for validating email addresses).

A problem that I have is that I am receiving a string which is comma separated, however some of the string values contain commas also. For example I might receive:

$COMMAND=1,2,3,"string","another,string",4,5,6

Generally I will never receive anything like this, however the device sending me this string array allows for it to happen so I would like to be able to split the array accordingly if it ever were to occur.

So obviously just splitting it like so (where rawResponse has the $COMMAND= part removed:

string[] response = rawResponse.Split(',');

Is not good enough! I think regex is the correct tool for the job, could anyone help me write it?

Upvotes: 0

Views: 123

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

string rawResponse = @"1,2,3,""string"",""another,string"",4,5";
string pattern = @"[^,""]+|""([^""]*)""";
foreach(Match match in  Regex.Matches(rawResponse, pattern))
       // use match.Value

Results:

1
2
3
"string"
"another,string"
4
5

If you need response as array of strings you can use Linq:

var response = Regex.Matches(rawResponse, pattern).Cast<Match>()
                    .Select(m => m.Value).ToArray();

Upvotes: 5

Basem Saadawy
Basem Saadawy

Reputation: 1818

string originalString = @"1,2,3,""string"",""another,string"",4,5,6";
string regexPattern = @"(("".*?"")|(.*?))(,|$)";
foreach(Match match in  Regex.Matches(originalString, regexPattern))
{

}

Upvotes: 0

Related Questions