Regex pattern to choose data BETWEEN matching quotation marks

后端 未结 5 910
悲哀的现实
悲哀的现实 2020-12-19 08:59

Suppose I had the following string I wanted to run a Regular expression on:

This is a test string with \"quotation-marks\" within it.
The \"problem\" I am ha         


        
5条回答
  •  北海茫月
    2020-12-19 09:58

    Instead of a regex, a regular method to do this might be more maintainable in the long run:

    public static String replaceDashInQuotes(this string source, String newValue)
    {
        StringBuilder sb = new StringBuilder();
    
        bool inquote = false;
    
        for (int i = 0; i < source.Length; i++)
        {
            if (source[i] == '\"')
                inquote = !inquote;
    
            if (source[i] == '-' && inquote)
                sb.Append(newValue);
            else
                sb.Append(source[i]);
        }
    
        return sb.ToString();
    }
    

    Then to use it:

    var s = @"This is a test string with ""quotation-marks"" within it.
        The ""problem"" I am having, per-se, is ""knowing"" which ""quotation-marks""
        go with which words.";
    
    MessageBox.Show(s.replaceDashInQuotes(" "));
    

提交回复
热议问题