c#中更有效的字符串解析方法

本文关键字:方法 字符串 有效 | 更新日期: 2023-09-27 18:15:10

读取文件并创建Regex组的代码。然后我遍历这些组,并使用关键字的其他匹配来提取我需要的内容。我需要每个关键字和下一个空格或换行符之间的东西。我想知道是否有一种方法使用Regex关键字匹配本身来丢弃我不想要的东西(关键字)。

//create the pattern for the regex
        String VSANMatchString = @"vsan's(?<number>'d+)[:'s](?<info>.+)'n('s+name:(?<name>.+)'s+state:(?<state>.+)'s+'n's+interoperability mode:(?<mode>.+)'s'n's+loadbalancing:(?<loadbal>.+)'s'n's+operational state:(?<opstate>.+)'s'n)?";
        //set up the patch
        MatchCollection VSANInfoList = Regex.Matches(block, VSANMatchString);
    // set up the keyword matches
    Regex VSANNum = new Regex(@" 'd* ");
Regex VSANName = new Regex(@"name:'S*");
Regex VSANState = new Regex(@"operational state'S*");

        //now we can extract what we need since we know all the VSAN info will be matched to the correct VSAN
        //match each keyword (name, state, etc), then split and extract the value
        foreach (Match m in VSANInfoList)
        {    
            string num=String.Empty;
            string name=String.Empty;
            string state=String.Empty;
            string s = m.ToString();
            if (VSANNum.IsMatch(s)) { num=VSANNum.Match(s).ToString().Trim(); }
            if (VSANName.IsMatch(s)) 
            {
                string totrim = VSANName.Match(s).ToString().Trim();
                string[] strsplit = Regex.Split (totrim, "name:");
                name=strsplit[1].Trim();
            }
            if (VSANState.IsMatch(s))
            {
                string totrim = VSANState.Match(s).ToString().Trim();
                string[] strsplit=Regex.Split (totrim, "state:");
                state=strsplit[1].Trim();
            }

c#中更有效的字符串解析方法

看起来您的单个正则表达式应该能够收集您需要的所有内容。试试这个:

string name = m.Groups["name"].Value; // Or was it m.Captures["name"].Value?