If I have a string like this
create myclass "56, 'for the better or worse', 54.781"
How can I parse it so that the result is three string words that have the following content:
[0] create [1] myclass [2] "56, 'for the better or worse', 54.781"
Edit 2: note that quotation marks must be kept
At first I tried to use string.Split(' ') , but I noticed that this would make the third string broken for several other strings.
I am trying to limit the result of Split using its count argument as 3 to solve this problem. And this is normal for this case, but when the given line
create myclass false "56, 'for the better or worse', 54.781" //or create myclass "56, 'for the better or worse', 54.781" false
Split then fails because the last two words will be combined.
I also created something like ReadInBetweenSameDepth to get the string between the quote
Here is my ReadInBetweenSameDepth method
//Examples: //[1] (2 + 1) * (5 + 6) will return 2 + 1 //[2] (2 * (5 + 6) + 1) will return 2 * (5 + 6) + 1 public static string ReadInBetweenSameDepth(string str, char delimiterStart, char delimiterEnd) { if (delimiterStart == delimiterEnd || string.IsNullOrWhiteSpace(str) || str.Length <= 2) return null; int delimiterStartFound = 0; int delimiterEndFound = 0; int posStart = -1; for (int i = 0; i < str.Length; ++i) { if (str[i] == delimiterStart) { if (i >= str.Length - 2) //delimiter start is found in any of the last two characters return null; //it means, there isn't anything in between the two if (delimiterStartFound == 0) //first time posStart = i + 1; //assign the starting position only the first time... delimiterStartFound++; //increase the number of delimiter start count to get the same depth } if (str[i] == delimiterEnd) { delimiterEndFound++; if (delimiterStartFound == delimiterEndFound && i - posStart > 0) return str.Substring(posStart, i - posStart); //only successful if both delimiters are found in the same depth } } return null; }
But although this function works, it was pretty difficult for me to combine the result with string.Split to do the right parsing as I want.
Edit 2: In my poor solution I need to add quotes again
Is there a better way to do this? If we use Regex , how to do it?
Edit:
I honestly do not suspect that this problem can be solved in the same way as text in CSV format. I also did not know that this problem was not always solved with the help of Regex (thus, I designated it as such). My sincere apology to those who see this as a duplicate message.
Edit 2:
After I worked more on my project, I realized that something was wrong with my question (that is, I did not include the quotation mark). My apology to the best defendant, Mr. Tim Schmelter. And then, looking at the dupe link, I noticed that it also does not provide an answer to this question.