使用C#在.NET 4.0中开发。 (对不起,如果这是啰嗦......)
我想创建一个方法,例如:
public static string GetCmdLineArgs(
string cmdLine,
string pathname )
{
...
}
我想创建一个正则表达式模式,让我在可执行文件的路径名后提取参数。规则:
我意识到我可以通过简单的System.String
操作一起破解这个功能,但我也想知道如何使用正则表达式匹配来保持未来变化的灵活性。
基本上,我想做类似的事情:
// 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...
}
显然,由于pathname
中存在正则表达式特殊字符,上述内容将无法正常工作。有没有办法修改它,所以它像我描述的那样工作?是否有一个分组运算符可以让我匹配一个未转义的字符串,还是我必须通过转义所有可能的特殊字符来转换pathname
?
如果已在其他地方询问并回答,请指出我的帖子。谢谢!
答案 0 :(得分:3)
见Regex.Escape
。我认为这是你唯一遗漏的东西。像
string pattern =
@"^\s*(?:""" + Regex.Escape(pathname) + """)?\s*(.*)";
答案 1 :(得分:0)
不要使用硬值但使用锚类型标记。在这个例子中,我知道 - 从具有“的路径中划分命令行选项。这样我已经对输出进行了标记化,并且可以提取参数的顺序和包含的路径。我正在使用If条件(? )在正则表达式中过滤掉路径项中的命令行参数。
string commandLine = @"-abc -log ""C:\Test it"" -def";
// \x22 is the escape for "
string pattern = @"
(?(\x22) # If a " then capture
((?:\x22)(?<Path>[^\x22]+)(?:\x22))
| # Or
((?:-)(?<Command>[^-\s]+)(?:\s?)) # It is a - and capture
)
";
var tokens = Regex.Matches(commandLine, pattern, RegexOptions.IgnorePatternWhitespace)
.OfType<Match>()
.Select (m => new
{
Arg = m.Groups["Command"].Value,
Path = m.Groups["Path"].Value
})
;
令牌的输出是: