0

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?

2
  • so, "another,string" = one unit? Commented Jan 13, 2013 at 15:57
  • Yes that's correct. It's not the intended use of the unit as I said, but it is allowed for some reason! Commented Jan 13, 2013 at 15:58

2 Answers 2

5
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();
Sign up to request clarification or add additional context in comments.

7 Comments

Excellent answer! Now I've integrated it, I will do my best to understand it! :D
Thanks for the ToArray example btw! +1 Is the m => m.Value known as a lambda expression or have I mis-remembered something else?
@ing0 it matches either one or more characters which is not comma or quotes, or it matches anything between quoutes (which is not quotes)
I understand that some people dislike regex but SO is not necessarily for opinions! I asked a question asking specifically for regex and with two or three lines of code in a answer I had the problem fixed within 5 minutes! Thanks again!
@lazyberezovsky - you know what, I had my coffee and thought better of it. I will remove the down vote asap :)
|
0
string originalString = @"1,2,3,""string"",""another,string"",4,5,6";
string regexPattern = @"(("".*?"")|(.*?))(,|$)";
foreach(Match match in  Regex.Matches(originalString, regexPattern))
{

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.