Developing in .NET 4.0 using C#. (Sorry if this is long-winded...)
I want to create a method such as:
public static string GetCmdLineArgs(
string cmdLine,
string pathname )
{
...
}
I want to create a Regex pattern that will let let me extract the arguments after the pathname of the executable file. The rules:
I realize that I could hack this function together by using simple System.String
operations, but I also want to know how to do it using Regex matching to preserve flexibility for future changes.
Basically, I want to do something like:
// Create the pattern:
// The pathname is anchored to the beginning of the pattern.
// The pathname group is non-capturing.
// Additional capture groups may be added in the future.
string pattern =
@"^\s*(?:""" + pathname + """)?\s*(.*)";
Regex regex = new Regex( pattern );
Match = regex.Match( cmdLine );
if ( match.Success )
{
// extract matching groups...
}
Obviously, the above won't work as-is because of the presence of Regex special characters in pathname
. Is there some way to modify this so it works as I've described? Is there a grouping operator that will let me match an unescaped string, or would I have to transform pathname
by escaping all possible special characters?
If this has been asked and answered elsewhere, please point me to that post. Thanks!
See Regex.Escape
. I think that's the only thing you're missing. Used like
string pattern =
@"^\s*(?:""" + Regex.Escape(pathname) + """)?\s*(.*)";