Prb Match RegEx

H

Horizon

Hi,

I would like to build a regex that returns me the table list of a SQL SELECT
request like :
-SELECT * FROM tab1, tab2, tab3
-SELECT * FROM tab1, tab2 WHERE col="abc"
-SELECT * FROM tab1, tab2 LIMIT 1

I tried something like that :
---
Regex pattern1 = new
Regex(@"FROM\s+(?<tabname>.*)(WHERE|LIMIT|ORDER|HAVING|GROUP)?",
RegexOptions.IgnoreCase );
Match match1 = pattern1.Match(request);
if( match1.Success )
string res = match1.Groups["tabname"].Value;
---

But, each time, in tabname, I get all the string to EOF.
For ex , in SELECT * FROM tab1, tab2 LIMIT 1
I get "tab1, tab2 LIMIT 1" instead of "tab1, tab2"


Thanks,
Horizon
 
N

Niki Estner

Horizon said:
Hi,

I would like to build a regex that returns me the table list of a SQL
SELECT request like :
-SELECT * FROM tab1, tab2, tab3
-SELECT * FROM tab1, tab2 WHERE col="abc"
-SELECT * FROM tab1, tab2 LIMIT 1

I tried something like that :
---
Regex pattern1 = new
Regex(@"FROM\s+(?<tabname>.*)(WHERE|LIMIT|ORDER|HAVING|GROUP)?",
RegexOptions.IgnoreCase );
Match match1 = pattern1.Match(request);
if( match1.Success )
string res = match1.Groups["tabname"].Value;
---

But, each time, in tabname, I get all the string to EOF.
For ex , in SELECT * FROM tab1, tab2 LIMIT 1
I get "tab1, tab2 LIMIT 1" instead of "tab1, tab2"

That's not surprising: "*" is a "greedy quantifier", i.e. it will match the
longest possible string. As "." matches any character, and everything after
that is optional, the leftmost longest match will be the whole string.

I'd suggest using a lazy quantifier (*?), and making the alternation
non-optional, like this:
Regex(
@"FROM\s+(?<tabname>.*?)(WHERE|LIMIT|ORDER|HAVING|GROUP|$)",
RegexOptions.IgnoreCase
| RegexOptions.Multiline
);

Hope this helps,

Niki
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top