簡體   English   中英

如何使用正則表達式從列表中提取字符串匹配?

[英]How can extract string matches using regular expression from a List?

我有一個列表,其中包含一些字符串和其他數據。

  HwndWrapper[App.exe;;cda6c3f4-8c87-4b12-8f3d-5322ca90eeex]
  HwndWrapper[App.exe;;cadac3f4-8c87-4b12-8q3d-1qwe2ca90eec]
  HwndWrapper[App.exe;;c1b6a3s4-8c87-4b12-8f3d-2qw2ca90eeev]

我的列表: // 返回 WindowInformation 對象的列表,其中包含 Handle、Caption、Class,//Parent、Children、Siblings 和進程信息

 List<WindowInformation> windowListExtended = WindowList.GetAllWindowsExtendedInfo();

要匹配的正則表達式是:

  HwndWrapper\[App.exe;;.*?\]

現在對於列表中的每場比賽。 我需要提取匹配的字符串並使用提取的每個字符串、Foreach 或類似的東西運行一個進程。

請幫忙。

更新:感謝 Altaris 的幫助,只需要將 List 轉換為字符串

        var message = string.Join(",", windowListExtended);
        string pattern = @"HwndWrapper\[LogiOverlay.exe;;.*?]";
        MatchCollection matches = Regex.Matches(message, pattern);

據我了解,您想在單獨的列表中提取每個匹配項以使用,go:

            var someList = new List<string>{"HwndWrapper[App.exe;;cda6c3f4-8c87-4b12-8f3d-5322ca90eeex]",
                                    "HwndWrapper[App.exe;;cadac3f4-8c87-4b12-8q3d-1qwe2ca90eec]",
                                    "HwndWrapper[App.exe;;c1b6a3s4-8c87-4b12-8f3d-2qw2ca90eeev]"};

            Regex FindHwndWrapper = new Regex(@"HwndWrapper\[App.exe;;(.*)\]");

            var matches = someList.Where(s => FindHwndWrapper.IsMatch(s)).ToList();

            foreach(var match in matches)
            {
                Console.WriteLine(match);// Use values
            }

我使用System.Linq function Where()來遍歷列表

如果您只需要 id 部分,請使用此 Linq 行,例如“cda6c3f4-8c87-4b12-8f3d-5322ca90eeex”

var matches = someList.Select(s => FindHwndWrapper.Match(s).Groups[1]).ToList();

我不確定你到底想要什么,我想你想提取這些

        List<string> windowListExtended = new List<string>();
        windowListExtended.Add("HwndWrapper[App.exe;;cda6c3f4-8c87-4b12-8f3d-5322ca90eeex]");
        windowListExtended.Add("HwndWrapper[App.exe;;cadac3f4-8c87-4b12-8q3d-1qwe2ca90eec]");
        windowListExtended.Add("HwndWrapper[App.exe;;c1b6a3s4-8c87-4b12-8f3d-2qw2ca90eeev]");

        var myRegex = new Regex(@"HwndWrapper\[App.exe;;.*?]");
        var resultList = files.Where(x => myRegex.IsMatch(x)).Select(x => x.Split(new[] { ";;","]" }, StringSplitOptions.None)[1]).ToList();

        //Now resultList contains => cda6c3f4-8c87-4b12-8f3d-5322ca90eeex, cadac3f4-8c87-4b12-8q3d-1qwe2ca90eec, c1b6a3s4-8c87-4b12-8f3d-2qw2ca90eeev
        foreach (var item in resultList)
        {
            //Do whatever you want
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM