【发布时间】:2017-08-12 16:59:03
【问题描述】:
我有以下简单的测试,我正在尝试获取正则表达式模式,以便它提取不带“.exe”后缀的可执行文件名称。
我的非捕获组设置 (?:\\.exe) 似乎不起作用,或者我误解了它的工作原理。
regex101 和 regexstorm.net 都显示相同的结果,前者确认 "(?:\.exe)" 是非捕获匹配。
关于我做错了什么有什么想法吗?
// test variable for what i would otherwise acquire from Environment.CommandLine
var testEcl = "\"D:\\src\\repos\\myprj\\bin\\Debug\\MyApp.exe\" /?"
var asmName = Regex.Match(testEcl, @"[^\\]+(?:\.exe)", RegexOptions.IgnoreCase).Value;
// expecting "MyApp" but I get "MyApp.exe"
我已经能够通过使用定义了组名的匹配模式来提取我想要的值,如下所示,但我想了解为什么非捕获组设置方法没有按我预期的方式工作到。
// test variable for what i would otherwise acquire from Environment.CommandLine
var testEcl = "\"D:\\src\\repos\\myprj\\bin\\Debug\\MyApp.exe\" /?"
var asmName = Regex.Match(Environment.CommandLine, @"(?<fname>[^\\]+)(?<ext>\.exe)",
RegexOptions.IgnoreCase).Groups["fname"].Value;
// get the desired "MyApp" result
/eoq
【问题讨论】:
-
要从
var testEcl = "\"D:\\src\\repos\\myprj\\bin\\Debug\\MyApp.exe\" /?"获取MyApp,您可以使用Path.GetFileName作为string directory = Path.GetFileName(testEcl); -
@Ashik,感谢基于非正则表达式的建议。尝试过 Path.GetFileName() 和 .GetFileNameWithoutExtension() 都抛出 System.ArgumentException "Illegal characters in path。"结果。
-
你的路径在开头和结尾都包含
"。尝试去掉引号,就可以了