有没有办法让RegEx.Replace中使用的变量在.NET中使用?

时间:2009-07-23 17:44:49

标签: c# regex

例如,我有一个我正在使用\G选项搜索的模式,因此它会记住它的最后一次搜索。我希望能够在.NET c#中重用这些(即:将匹配保存到集合中)

例如:

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

我希望这很清楚,如果没有,我可以详细说明。

谢谢: - )

2 个答案:

答案 0 :(得分: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;
        }

答案 1 :(得分:0)

这个简单吗?

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