If I have a string
like this
create myclass \"56, \'for the better or worse\', 54.781\"
How can I parse it such that the resul
Regex Demo
(\w+|"[^"]*")
Get the matches in the first capture group.
\w+
: Matches alphanumeric characters and underscore one or more times"[^"]*"
: Matches anything that is wrapped in double quotes|
: OR condition in regexI would use a real csv-parser for this task. The only one available in the framework is the TextFieldParser-class in the VisualBasic namespace:
string str = "create myclass \"56, 'for the better or worse', 54.781\"";
var allLineFields = new List<string[]>();
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(str)))
{
parser.Delimiters = new string[] { " " };
parser.HasFieldsEnclosedInQuotes = true; // important
string[] lineFields;
while ((lineFields = parser.ReadFields()) != null)
{
allLineFields.Add(lineFields);
}
}
Result:
But there are others available like this or this.
You can split by this
\s(?=(?:[^"]*"[^"]*")*[^"]*$)
See demo.
https://regex101.com/r/fM9lY3/60
string strRegex = @"\s(?=(?:[^""]*""[^""]*"")*[^""]*$)";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline);
string strTargetString = @"create myclass ""56, 'for the better or worse', 54.781""";
return myRegex.Split(strTargetString);