使用常规的前pression更换空白外报价常规、空白、pression

2023-09-02 12:00:20 作者:熟男日记

使用C#,我需要prepare搜索文本由以%字符替换所有的空白之外引号使用LIKE命令在SQL Server数据库中搜索。例如:

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. Example:

输入:

my "search text"

输出:

%my%search text%

任何帮助将是AP preciated。替换文本之前,我可以处理输入的字符串加引号的奇数。

Any help would be appreciated. I can handle input strings with an odd number of quotes before replacing the text.

推荐答案

如果您的有无的使用正则表达式,你可以做到这一点,如果你是确保所有报价都是正确的平衡,如果有没有逃脱引号( )的字符串中(有可能考虑到这些,太,但它使正则表达式更加复杂)。

If you have to use a regex, you can do it if you are sure that all quotes are correctly balanced, and if there are no escaped quotes (") in the string (it is possible to account for those, too, but it makes the regex even more complicated).

resultString = Regex.Replace(subjectString, 
    @"[ ]       # Match a space (brackets for legibility)
    (?=          # Assert that the string after the current position matches...
     [^""]*      # any non-quote characters
     (?:         # followed by...
      ""[^""]*   # one quote, followed by 0+ non-quotes
      ""[^""]*   # a second quote and 0+ non-quotes
     )*          # any number of times, ensuring an even number of quotes
    $            # until the end of the string
    )            # End of lookahead", 
    "%", RegexOptions.IgnorePatternWhitespace);

这将检查字符串的其余部分当前空间字符之后断言偶数行情。先行的(感谢阿兰·摩尔!)的优势在于,它比后向更轻便(除了.NET最正则表达式的口味和其他几个人不支持内后向断言无限期重复)。它也可能会更快。

This examines the remainder of the string to assert an even number of quotes after the current space character. The advantage of lookahead (thanks Alan Moore!) is that it's more portable than lookbehind (most regex flavors except .NET and a few others don't support indefinite repetition inside lookbehind assertions). It may also well be faster.

涉及后向原来的解决方案如下:

The original solution involving lookbehind is as follows:

resultString = Regex.Replace(subjectString, 
    @"(?<=       # Assert that the string up to the current position matches...
    ^            # from the start of the string
     [^""]*      # any non-quote characters
     (?:         # followed by...
      ""[^""]*   # one quote, followed by 0+ non-quotes
      ""[^""]*   # a second quote and 0+ non-quotes
     )*          # any number of times, ensuring an even number of quotes
    )            # End of lookbehind
    [ ]          # Match a space (brackets for legibility)", 
    "%", RegexOptions.IgnorePatternWhitespace);