简体   繁体   English

正则表达式解析SQL字符串

[英]Regex parse sql string

I have sql string like 我有像SQL字符串

select * from dbo.Person where Person  = ? AND Name = ? OR (Country = ? OR City = 1)

If it's possible to get string array like below with Regex in C# 如果可以在C#中使用Regex获取如下所示的字符串数组

result[0] = Person = ?
result[1] = Name = ?
result[2] = (Country = ? OR City = 1)

thanks. 谢谢。

If you need anything more complicated than this, it's going to quickly go beyond what you can easily solve with regex. 如果您需要比这更复杂的东西,它将很快超出使用正则表达式可以轻松解决的范围。 I have released a free parser on GitHub that will parse out TSQL in a stable way into the pieces, TSQL Parser . 我已经在GitHub上发布了一个免费的解析器,它将以稳定的方式将TSQL解析TSQL Parser You can also use the Microsoft TSQL parser, using the TSqlParser . 您还可以使用TSqlParser使用Microsoft TSQL解析器。 With either of these, they will break it out a little more granular than you're requesting, which you will then have to piece back together based on parenthesis for example. 无论使用哪种方法,他们都会将其分解为比您要求的粒度更细的粒度,然后您必须基于括号将其拼凑起来。

First try looks like this 第一次尝试看起来像这样

var s = @"select* from dbo.Person where Person = ? AND Name = ? OR (Country = ? OR City = 1)";

 var reg = new Regex("[A-Za-z]+ = [A-Za-z0-9?]+");

var result =  reg.Matches(s);

Something like that but is no Regex 那样的东西,但不是正则表达式

  var s = @"select* from dbo.Person where Person = ? AND Name = ? OR(Country = ? OR City = 1)";

  var s1 = s.Split(new[] { "where" }, StringSplitOptions.None)[1];

  var s2 = s1.Split(new[] { "OR", "AND" }, StringSplitOptions.None);

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

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