0

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.

  • 2
    Do you really want to parse sql yourself? If so, why? – Tim Schmelter Jan 22 '16 at 12:15
  • what you mean by `from dbo.Person where Person` is person is table name as well as column name? – sujith karivelil Jan 22 '16 at 12:16
  • 1
    Is this necessary for a real world application? If so, in my humble opinion, it shouldn't.. – Soner Gönül Jan 22 '16 at 12:18
  • Yes It is Possible so for you make the regex and for that you use Regex.Matches(string, regex) . – KARAN Jan 22 '16 at 12:19
  • 1
    .NET has this functionality built in. Look [here](https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.sqlparser.parser.aspx) and [here](http://stackoverflow.com/questions/30452864/parsing-t-sql-statements-to-tokens) – Icemanind Jan 22 '16 at 23:51

2 Answers2

1

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);
blogprogramisty.net
  • 1,714
  • 1
  • 18
  • 22
  • You regex doesn't match `result[2] = (Country = ? OR City = 1)` as one match. [It](https://regex101.com/r/bB0sK0/1) matches `Country = ?` and `City = 1` as two different matches. –  Jan 22 '16 at 21:49
1

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.

Community
  • 1
  • 1
Bruce Dunwiddie
  • 2,888
  • 1
  • 15
  • 20