【问题标题】:Search text file for text above which pattern matches input在文本文件中搜索模式匹配输入的文本
【发布时间】:2016-05-24 09:03:17
【问题描述】:

我正在尝试让我的程序显示与我设置的模式匹配的输入文本上方的文本。

例如,如果用户输入 'FastModeIdleImmediateCount"=dword:00000000',我应该得到上面最接近的 HKEY,对于这种情况,它是 [HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000]。

[HKEY_CURRENT_CONFIG\System\CurrentControlSet\Enum\SCSI\Disk&Ven_ATA&Prod_TOSHIBA_MQ01ABD0\4&6a0976b&0&000000]
"StandardModeIdleImmediateCount"=dword:00000000
"FastModeIdleImmediateCount"=dword:00000000

[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES]

[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD]

[HKEY_CURRENT_CONFIG\System\CurrentControlSet\SERVICES\TSDDD\DEVICE0]
"Attach.ToDesktop"=dword:00000001

谁能告诉我如何编写这样的代码?我尝试使用正则表达式来匹配带有括号的文本,但我不知道如何让它只搜索我输入上方的文本。

【问题讨论】:

  • 请提供更多详细信息...文本来源是什么?您是否在 Windows 注册表上执行搜索?你想匹配键还是值?

标签: c# .net visual-studio c#-4.0 registry


【解决方案1】:

我假设您的文件是 .txt 文件,但很可能不是。但逻辑是一样的。 这一点都不难,一个简单的 for() 循环就可以了。 带有所需描述的代码:

string[] lines = File.ReadAllLines(@"d:\test.txt");//replace your directory. We're getting all lines from a text file.

        string inputToSearchFor = "\"FastModeIdleImmediateCount\"=dword:00000000";  //that's the string to search for

        int indexOfMatchingLine = Array.FindIndex(lines, line => line == inputToSearchFor); //getting the index of the line, which equals the matchcode

        string nearestHotKey = String.Empty;
        for(int i = indexOfMatchingLine; i >=0; i--)    //looping for lines above the matched one to find the hotkey
        {               
            if(lines[i].IndexOf("[HKEY_") == 0)         //if we find a line which begins with "[HKEY_" (that means it's a hotkey, right?)
            {
                nearestHotKey = lines[i];               //we get the line into our hotkey string
                break;                                  //breaking the loop
            }
        }

        if(nearestHotKey != String.Empty)               //we have actually found a hotkey, so our string is not empty
        {
            //add code...
        }

【讨论】:

    【解决方案2】:

    您可以尝试将文本分成几行,找到包含您的文本的行的索引(无论使用完全匹配还是正则表达式都无关紧要),然后反向搜索第一个键。首先对行进行反向排序可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-26
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 2015-01-18
      • 1970-01-01
      • 2016-07-09
      相关资源
      最近更新 更多