Replace whitespace outside quotes using regular expression

前端 未结 5 855
天涯浪人
天涯浪人 2020-12-11 20:05

Using C#, I need to prepare a search text for searching in a SQL Server database using the LIKE command by replacing all whitespace outside quotes with a % character. Exampl

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 20:20

    Would have done something like this:

     private static string RemoveUnquotedWhiteSpaces(string text)
     {    
        string result = String.Empty;
        var parts = text.Split('"');
        for(int i = 0; i < parts.Length; i++)
        {
           if (i % 2 == 0) result += Regex.Replace(parts[i], " ", "");
           else result += String.Format("\"{0}\"", parts[i]);
        }
        return result
      }
    

提交回复
热议问题