Replace whitespace outside quotes using regular expression

前端 未结 5 852
天涯浪人
天涯浪人 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:21

    It looks like you also want to remove the quotation marks and add a % to the beginning and end of the search string. Try this:

    string s0 = @"my ""search text""";
    
    Regex re = new Regex(@"(?x)
        (?:
           (?[^\s""]+)
         |
           ""(?[^""]+)""
        )
        (?:\s+|$)");
    
    string s1 = @"%" + re.Replace(s0, @"${term}%");
    Console.WriteLine(s1);
    

    output:

    %my%search text%
    

提交回复
热议问题