Prb Match RegEx

  • Thread starter Thread starter Horizon
  • Start date Start date
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
 
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
 
Back
Top