繁体   English   中英

C#正则表达式提取字符串括在单引号中

[英]C# regex extract string enclosed into single quotes

我需要使用RegEx解析以下字符串。

abc = 'def' and size = '1 x(3\" x 5\")' and (name='Sam O\'neal')

这是一个SQL过滤器,我想使用以下分隔符将其拆分为标记:

(, ), >,<,=, whitespace, <=, >=, !=

在解析字符串之后,我希望输出为:

abc,
=,
def,
and,
size,
=,
'1 up(3\" x 5\")',
and,
(,
Sam O\'neal,
),

我试过以下代码:

string pattern = @"(<=|>=|!=|=|>|<|\)|\(|\s+)";
var tokens = new List<string>(Regex.Split(filter, pattern));
tokens.RemoveAll(x => String.IsNullOrWhiteSpace(x));

我不确定如何将单引号中的字符串保留为一个标记。 我是Regex的新手,非常感谢任何帮助。

您的模式需要使用另一个替代分支进行更新: '[^'\\\\]*(?:\\\\.[^'\\\\]*)*'

它将匹配:

  • ' - 单引号
  • [^'\\\\]* - 除了'\\之外' 0+字符
  • (?: - 非捕获组匹配序列:
    • \\\\. - 任何逃脱序列
    • [^'\\\\]* - 除了'\\之外' 0+字符
  • )* - 零次或多次出现
  • ' - 单引号

在C#中:

string pattern = @"('[^'\\]*(?:\\.[^'\\]*)*'|<=|>=|!=|=|>|<|\)|\(|\s+)";

请参阅正则表达式演示

C#demo

var filter = @"abc = 'def' and size = '1 x(3"" x 5"")' and (name='Sam O\'neal')";
var pattern = @"('[^'\\]*(?:\\.[^'\\]*)*'|<=|>=|!=|=|>|<|\)|\(|\s+)";
var tokens = Regex.Split(filter, pattern).Where(x => !string.IsNullOrWhiteSpace(x));
foreach (var tok in tokens)
    Console.WriteLine(tok);

输出:

abc
=
'def'
and
size
=
'1 x(3" x 5")'
and
(
name
=
'Sam O\'neal'
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM