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.

5
  • 2
    Do you really want to parse sql yourself? If so, why? Commented Jan 22, 2016 at 12:15
  • what you mean by from dbo.Person where Person is person is table name as well as column name? Commented Jan 22, 2016 at 12:16
  • 1
    Is this necessary for a real world application? If so, in my humble opinion, it shouldn't.. Commented Jan 22, 2016 at 12:18
  • Yes It is Possible so for you make the regex and for that you use Regex.Matches(string, regex) . Commented Jan 22, 2016 at 12:19
  • 1
    .NET has this functionality built in. Look here and here Commented Jan 22, 2016 at 23:51

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You regex doesn't match result[2] = (Country = ? OR City = 1) as one match. It matches Country = ? and City = 1 as two different matches.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.