tags:

views:

30

answers:

1

Hi guys,

Could you help me to understand what is wrong. I have usual SQL query :

var SQL = "SELECT [Extent1].[RouteID] AS [RouteID]
           FROM  [RoutesEntities].[Routes] AS [Extent1]\r\n
           INNER JOIN [dbo].[Locales] AS [Extent2] 
           ON [Extent2].[LocaleID] = [Extent1].[LocaleID]";

And i need to define location of FROM part till its AS alias. I did the following with RegEx.Replace :

var pattern = @"(FROM[^(SELECT)]+?Routes.+?AS.+?\[?([^\]\s]+)\]?)";
var result = Regex.Replace(SQL, pattern, "$1 $2", RegexOptions.Singleline | RegexOptions.IgnoreCase);

And it works fine - this will return :

match_$1 = "FROM  [RoutesEntities].[Routes] AS [Extent1]";
match_$2 = "Extent1";

BUT! If i try to use Regex.Matches with the same options and same input string ... it finds only one match.

MatchCollection queryPlace = Regex.Matches(
                SQL, 
                @"(FROM[^(SELECT)]+?Routes.+?AS.+?\[?([^\]\s]+)\]?)", 
                RegexOptions.IgnoreCase | RegexOptions.Singleline
);

match_$1 = "FROM  [RoutesEntities].[Routes] AS [Extent1]";

WHY??? Is this a bug, or i should create a separate named group for each sub expression? Does anybody know why this happens, why only first match was found?

P.S. Regex is correct - i'm sure, you can check it here - http://www.gskinner.com/RegExr/

Thank, Artem

A: 

Sorry, I think i was so stupid, i do not know what does Regex.Matches method for, but i understood that in any case i should use Regex.Match and then use its Groups property :

Match queryPlace = Regex.Match(
                _queryData.CommandText, 
                @"(FROM[^(SELECT)]+?" + tableInner + @".+?AS.+?\[?([^\]\s]+)\]?)", 
                RegexOptions.IgnoreCase | RegexOptions.Singleline
            );
            String innerAlias = "";
var d = queryPlace.Groups[0];     // FROM [RoutesEntities].[Routes] AS [Extent1]
var d1 = queryPlace.Groups[1];    // FROM [RoutesEntities].[Routes] AS [Extent1]
var d2 = queryPlace.Groups[2];    // Extent1

Sorry for disturbing, answer is found.

Tema