Suppose, I've the following string:
string str = "'Hello, how are you?', 'your name', what you want";
I can replace the single quote and comma with the followings:
str.Replace("'", "''");
string[] word = str.Split(',');
I was wondering how could I get the output like the below:
Hello, how are you? your name what you want
The comma inside the single quote will not be replaced, only outside of it.
You can accomplish this using Regular Expressions:
private const string SPLIT_FORMAT = "{0}(?=(?:[^']*'[^']*')*[^']*$)";
public static string SplitOutsideSingleQuotes(this string text, char splittingChar)
{
string[] parts = Regex.Split(text, String.Format(SPLIT_FORMAT, splittingChar), RegexOptions.None);
for (int i = 0; i < parts.Length; i++)
{
parts[i] = parts[i].Replace("'", "");
}
return String.Join("", parts);
}
The code uses the expression to split on the splittingChar
outside of single quotes. It then replaces each single quote in the resultant string array. Lastly it joins the parts back together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With