How can I remove quoted string literals from a string in C #?

I have a line:

Hi "quoted string" and "tricky" stuff 'world

and want to return a line minus quotes. For instance.

Hello and peace

Any suggestions?

+3
source share
3 answers
resultString = Regex.Replace(subjectString, 
    @"([""'])# Match a quote, remember which one
    (?:      # Then...
     (?!\1)  # (as long as the next character is not the same quote as before)
     .       # match any character
    )*       # any number of times
    \1       # until the corresponding closing quote
    \s*      # plus optional whitespace
    ", 
    "", RegexOptions.IgnorePatternWhitespace);

will work on your example.

resultString = Regex.Replace(subjectString, 
    @"([""'])# Match a quote, remember which one
    (?:      # Then...
     (?!\1)  # (as long as the next character is not the same quote as before)
     \\?.    # match any escaped or unescaped character
    )*       # any number of times
    \1       # until the corresponding closing quote
    \s*      # plus optional whitespace
    ", 
    "", RegexOptions.IgnorePatternWhitespace);

will also handle escaped quotes.

So, it will convert correctly

Hello "quoted \"string\\" and 'tricky"stuff' world

at

Hello and world
+8
source

Use a regular expression to match any quoted strings with a string and replace them with an empty string. Use the method Regex.Replace()to match and replace patterns.

+1
source

, , , . , , .

private static string RemoveQuotes(IEnumerable<char> input)
{
    string part = new string(input.TakeWhile(c => c != '"' && c != '\'').ToArray());
    var rest = input.SkipWhile(c => c != '"' && c != '\'');
    if(string.IsNullOrEmpty(new string(rest.ToArray())))
        return part;
    char delim = rest.First();
    var afterIgnore = rest.Skip(1).SkipWhile(c => c != delim).Skip(1);
    StringBuilder full = new StringBuilder(part);
    return full.Append(RemoveQuotes(afterIgnore)).ToString();
}
0
source

All Articles