C#和Regex-无法识别的分组构造

本文关键字:识别 Regex- | 更新日期: 2023-09-27 18:28:24

目前正在为客户端/服务器应用程序撰写论文。我遇到了一个障碍,服务器接收到这样的信息:

ProToCooL,unknown|DESKTOP-29COFES,10.20.9.53|Hewlett-Packard,179C,PCWJA001X3UHII,KBC Version 42.32|i5-3320M,2.60GHz,2,4,256,3072,U3E1,GenuineIntel|{2,(IDT High Definition Audio CODEC,IDT),(Intel(R) Display Audio,Intel(R) Corporation)}|{2,(Samsung,003355A3,M471B5773DH0-CH9  ,24,2147483648,1333),(Hynix/Hyundai,467CA639,HMT351S6EFR8A-PB  ,24,4294967296,1333)}|{1,(IDE,Hitachi HTS725050A7E630,      FT51009Y7J61BK,3,733004892,476937.531738281)}|{7,(Send To OneNote 2013,False,Local,Send to Microsoft OneNote 15 Driver),(Microsoft XPS Document Writer,False,Local,Microsoft XPS Document Writer v4),(Microsoft Print to PDF,False,Local,Microsoft Print To PDF),(HP Universal Printing PCL 6,False,Local,HP Universal Printing PCL 6),(HP LaserJet P3010 Series (10.20.9.36),False,Local,HP Universal Printing PCL 6),(Fax,False,Local,Microsoft Shared Fax Driver),(Adobe PDF,True,Local,Adobe PDF Converter)}

我已经建立了当前的模式:

'(((?:[^()]|(?R))+)')

它很好地提取了我需要的一切,但问题是当我在C#中以这种方式使用它时:

if(soundCount > 0)
        {
            string[] smth;
            string pattern = @"'(((?:[^()]|(?R))+)')";
            Regex match = new Regex(pattern, RegexOptions.None);
            MatchCollection matches = match.Matches(sound);
            smth = new string[matches.Count];
            int i=0;
            foreach (Match ma in matches)
            {
                smth[i] = Regex.Replace(ma.Value.Trim('(', ')'), @"'s+", "");
                Console.WriteLine(smth[i]);
                i++;
            }

            IList<sound_chips> newSoundchip = new List<sound_chips>();
            foreach(string s in smth)
            {
                newSoundchip.Add(new sound_chips() 
                { 
                    name = s.Split(',')[0].ToString(), 
                    manufacturer_id = Convert.ToInt32(setManufacturer(s.Split(',')[1].ToString())),
                    motherboards = newMotherboard
                });
            }
            insert.sound_chips.AddRange(newSoundchip);
        }

我得到一个:无法识别的分组构造。异常,我很难找到问题所在,因为我对C#的regexp并没有那么了解,也没有找到解决问题的方法。

C#和Regex-无法识别的分组构造

.NET正则表达式不支持递归。您正在使用的正则表达式('(((?:[^()]|(?R))+)'))用于PCRE,您可以将其与C#应用程序中的PCRE.NET库一起使用。

作为替代方案,您可以使用.NET正则表达式来匹配平衡括号:

'(((?>[^()]+|'((?<n>)|')(?<-n>))+(?(n)(?!)))')

请参阅regex演示。

它将所有这12个匹配项作为PCRE正则表达式返回。