Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single Qoute Replacement Without Comma in String

Tags:

c#

asp.net

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.

like image 476
AT-2017 Avatar asked Feb 07 '23 11:02

AT-2017


1 Answers

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.

like image 200
TheLethalCoder Avatar answered Feb 12 '23 12:02

TheLethalCoder