我有一个C#应用程序,我正在使用RegEx从Unix响应运行expect。我现在有这个。
//will pick up :
// What is your name?:
// [root@localhost ~]#
// [root@localhost ~]$
// Do you want to continue [y/N]
// Do you want to continue [Y/n]
const string Command_Prompt_Only = @"[$#]|\[.*@(.*?)\][$%#]";
const string Command_Question_Only = @".*\?:|.*\[y/N\]/g";
const string Command_Prompt_Question = Command_Question_Only + "|" + Command_Prompt_Only;这是我在www.regexpal.com中测试过的,但是我认为我需要一些优化,因为有时候,当我使用Command_Prompt_Question时,它似乎会慢下来。
var promptRegex = new Regex(Command_Prompt_Question);
var output = _shellStream.Expect(promptRegex, timeOut);我可能需要提到我正在使用SSH.NET与这些Linux服务器对话,但我不认为这是一个SSH.NET问题,因为当我使用Command_Prompt_Only时它是快速的。
有人看到我正在使用的const字符串有什么问题吗?有更好的方法吗?
我的项目是开源的,如果你想玩的话。
https://github.com/gavin1970/Linux-Commander
相关代码:https://github.com/gavin1970/Linux-Commander/blob/master/Linux-Commander/common/Ssh.cs
我正在尝试构建一个带有Ansible支持的虚拟Linux控制台。
发布于 2020-09-22 23:22:25
试试这个:
class Foo
{
const string Command_Prompt_Only = @"[$#]|\[.*@(.*?)\][$%#]";
const string Command_Question_Only = @".*\?:|.*\[y/N\]";
const string Command_Prompt_Question = "(?:" + Command_Question_Only + ")|(?:" + Command_Prompt_Only + ")";
private static readonly Regex _promptRegex = new Regex( Command_Prompt_Question, RegexOptions.Compiled );
public void Foo()
{
// ...
var output = _shellStream.Expect( _promptRegex, timeOut );
}
}发布于 2020-09-22 23:37:18
有人看到我正在使用的const字符串有什么问题吗?
是的,在这些模式中有太多的回溯。
如果知道至少有一个项,那么指定一个* (0或更多)会导致解析器查看许多零类型断言。更好的选择是+(一个或多个)乘法器,它可以节省大量的时间来研究回溯的死胡同。
这是有趣的\[.*@(.*?)\],为什么不使用负集([^ ])模式来代替这种更改:
\[[^@]+@[^\]+\]
它将一个文字"[“和非文字"@”([^@]+)的查找1或多个项锚定,然后通过[^\]+查找一个或多个非文字"]“项。
https://stackoverflow.com/questions/64018378
复制相似问题