2011-11-20 74 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時需要訪問哪些屬性。 –