Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match common SQL syntax?

I was writing some Unit tests last week for a piece of code that generated some SQL statements.

I was trying to figure out a regex to match SELECT, INSERT and UPDATE syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up.

I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement.

Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them.

By the way it's C# RegEx that I'm after.

Clarification

I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project.

like image 965
Omar Kooheji Avatar asked Sep 26 '08 14:09

Omar Kooheji


People also ask

How do you match a regular expression?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Can you use regular expressions in SQL Server?

Regular expressions are a concise and flexible notation for finding and replacing patterns of text. A specific set of regular expressions can be used in the Find what field of the SQL Server Management Studio Find and Replace dialog box.

What is the correct syntax to use regular expression in queries in MySQL?

A string expression. A pattern whose match is to be found in the expression. Note: As MySQL uses the C escape syntax in strings (for example, “\n” to represent the newline character), you must double any “\” that you use in your REGEXP strings. REGEXP is not case sensitive, except when used with binary strings.


1 Answers

Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. It can be demonstrated you can't validate SQL with a regex. So, you can stop trying.

like image 194
Pablo Marambio Avatar answered Oct 08 '22 19:10

Pablo Marambio