gpt4 book ai didi

c# - 解析命令行的正则表达式

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:55 24 4
gpt4 key购买 nike

我需要一个正则表达式来解析如下命令:

C:\Program Files\Internet Explorer\iexplore.exe https:\www.google.com
C:\Program Files\Internet Explorer\iexplore.exe http:\www.google.com
C:\Program Files\Internet Explorer\iexplore.exe www.google.com
iexplore.exe https:\www.google.com
copy C:\test.txt D:\

关键是我想将第一部分作为命令,将其他部分作为参数。命令可以是任何东西,包括.bat.vbs.exe

找到一个正则表达式,如果命令中没有空格,它可以正常工作。

string str = @"C:\xcopy D:\test.txt D:\Test";

string pattern = @"^(?:""([^""]*)""\s*|([^""\s]+)\s*)+";
Regex parseDir = new Regex(pattern, RegexOptions.IgnoreCase);
if(parseDir.IsMatch(str))
{
Match dir = parseDir.Match(str);
var captures = dir.Groups[1].Captures.Cast<Capture>().Concat(
dir.Groups[2].Captures.Cast<Capture>()).
OrderBy(x => x.Index).
ToArray();
string cmd = captures[0].Value;
string arguments = string.Empty;
for (int i = 1; i < captures.Length; i++)
{
arguments += captures[i].Value + " ";
}
Console.WriteLine(cmd);
Console.WriteLine(arguments);
}

最佳答案

根据您的问题,我假设您正在寻找一种在 Windows 操作系统上以文本形式传递批处理命令的方法。我能想到的让你成功做到这一点的唯一方法是,如果你有所有命令的列表,或者如果你的程序可以提取系统中的所有 .exe 文件,这样你就可以成功地检查第一个 exe 文件在哪里 < em>命令的目标程序是并假设其他的作为参数。

这样,您就可以像这样进行提取(非正则表达式方法):

var cmd = "copy this.txt C:\t.txt"
var program = getTargetProgram(cmd);
var args = cmd.Substring(cmd.IndexOf(program) + program.length).trim().split(' ');

您的 getTargetProgram() 可以像这样:

private string getTargetProgram(string cmd)
{
//first test if it's a normal executable
if(File.Exists(cmd.Substring(0, cmd.IndexOf(".exe") + 4)) //return this extract;
foreach(string s in winProgramList)
{
if(cmd.StartsWith(s)){
//voila, we can return the target
}
}
}

关于c# - 解析命令行的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com