简体   繁体   中英

Regex parse sql string

I have sql string like

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#

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 . You can also use the Microsoft TSQL parser, using the TSqlParser . 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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