2009-07-23 78 views
0

例如,我有一個模式,我正在使用\G選項搜索,因此它會記住它的上一次搜索。我希望能在.NET C#重用這些(即:保存匹配到一個集合)有沒有辦法讓在RegEx.Replace中使用的變量在.NET中使用?

例如:

string pattern = @"\G<test:Some\s.*"; 
string id = RegEx.Match(orig, pattern).Value; 
// The guy above has 3 matches and i want to save all three into a generic list 

我希望這是明確的,我如果不細說。

感謝:-)

+0

如果你給一個完整的例子,這將有所幫助。 – 2009-07-23 17:53:49

回答

1

試試這個:

private void btnEval_Click(object sender, EventArgs e) 
     { 
      txtOutput.Text = ""; 
      try 
      { 
       if (Regex.IsMatch(txtInput.Text, txtExpression.Text, getRegexOptions())) 
       { 
        MatchCollection matches = Regex.Matches(txtInput.Text, txtExpression.Text, getRegexOptions()); 

        foreach (Match match in matches) 
        { 
         txtOutput.Text += match.Value + "\r\n"; 
        } 

        int i = 0; 
       } 
       else 
       { 
        txtOutput.Text = "The regex cannot be matched"; 
       } 
      } 
      catch (Exception ex) 
      { 
       // Most likely cause is a syntax error in the regular expression 
       txtOutput.Text = "Regex.IsMatch() threw an exception:\r\n" + ex.Message; 
      } 

     } 

     private RegexOptions getRegexOptions() 
     { 
      RegexOptions options = new RegexOptions(); 

      return options; 
     } 
0

這個簡單的?

List<string> matches = new List<string>(); 
matches.AddRange(Regex.Matches(input, pattern)); 
相關問題