.
by default does not match newlines. You might solve the problem with RegexOptions.Singleline:
private static readonly Regex MethodNamesExtractor = new Regex(@"^.*(\S*)\({1}.*ref\s*SqlConnection", RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.Compiled);
The Multiline
option makes ^
and $
match at every beginning and end of a line respectively instead of matching the beginning and end of the whole string. It might be a little confusing, but that's how it is! And you can use an inline modifier which works just the same (?s)
. I'll use that in the subsequent regexes, and remove the Multiline
mode since it's not being used.
But that's not the only problem. .*
will not match greedily, meaning that it will match as much as possible, before \S*
even has the chance to match something. You can fix this by making .*
lazy, i.e. by adding a ?
to it, or simply removing it, since it isn't doing much anyway. Also {1}
is redundant, since repetition of once is the default quantifier. Also, the ^.*
at the beginning isn't doing much You can safely remove it:
private static readonly Regex MethodNamesExtractor = new Regex(@"(?s)(\S*)\(.*ref\s*SqlConnection", RegexOptions.Compiled);
Now for the tricky part: if you are now trying to match several method names from many methods, the above regex will match only one. Let's say you are trying to get the method names from two methods, the first one doesn't have the req SqlConnection
part while the second one does. Well, you get this.
To fix that, you might want to restrict .*
to a negated class, by using [^)]*
. You will notice that using this won't give you any match, and that's because of a commented part in the method which has a )
just before the req SqlConnection
part appears. Well, you can allow for commented lines like this:
"(?s)(\S*)\((?:[^)]|//[^\r\n]*\))*ref\s*SqlConnection"
That's provided you don't have any 'false' double forward slashes or parens within the parameters. To allow comment blocks too, well, the regex will become longer, obviously... (and even longer if you want to allow parens within the parameters)
"(?s)(\S*)\((?:[^)]|//[^\r\n]*\)|/\*(?:(?!\*/).)*\*/)*ref\s*SqlConnection"
Well, conclusion, it might be better to use a dedicated parser to parse a programming language.