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

时间:2011-11-20 02:37:28

标签: c# regex

我有这个代码读取文件并创建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();
            }

1 个答案:

答案 0 :(得分:1)

看起来你的单一正则表达式应该能够收集你所需要的一切。试试这个:

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