2011-11-20 38 views
0

我有这段代码读取文件并创建正则表达式组。然后,我浏览这些组并使用关键字上的其他匹配来提取我需要的内容。我需要每个关键字和下一个空格或换行符之间的内容。我想知道是否有一种方法使用正则表达式关键字匹配本身来放弃我不想要的(关键字)。更高效的方式来解析C中的字符串#

//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(); 
      } 
+3

你能提供一些样本输入和期望的输出吗? – Jay

回答

1

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

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

谢谢。那是我需要的。我找不到我想要在线的例子,并且不清楚我在调试器中查看MatchCollection时需要访问哪些属性。 –