C# RegEx.Matches doesn't return all submatches inside expression unlike RegEx.Replace
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 w开发者_Python百科ill 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
Sorry, I think i was so stupid because i did not know how exactly Regex.Matches method works and now i understood that in any case i should use Regex.Match and 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.
精彩评论