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

前端 未结 3 503
遇见更好的自我
遇见更好的自我 2021-01-21 00:28

I have a string:

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

and want to get the string minus the quoted parts back. E.g.,

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-21 01:06

    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 correctly transform

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

    into

    Hello and world
    

提交回复
热议问题