正则表达式。用引号中的最后一个隔离三个单词的字符串

时间:2014-02-11 07:31:48

标签: c# regex

请看,我如何在C#中创建正则表达式,这是一个由三个单词组成的序列,最后一个单词用双引号括起来。 Example.from string应该是isolate substring:

  

设置vrouter“Trust-Gi”

。我有这样的代码,但是常规exp错了..

        private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog opendialog = new OpenFileDialog();
        if (opendialog.ShowDialog() == DialogResult.OK)
        {
            var lines = File.ReadLines(opendialog.FileName);
            string pattern = @"set vrouter ".*"";
            foreach (var line in lines)
            {
                var matches = Regex.Matches(line, pattern);
                foreach (Match match in matches)
                {
                    if (match.Success)
                        textBox1.AppendText(match.Value + '\n');
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

Match m = Regex.Match(input, @"(\w+)\s+(\w+)\s+""([\w-]+)""");

给定输入set vrouter "Trust-Gi",匹配组将包含以下内容:

// m.Groups[1].Value == set
// m.Groups[2].Value == vrouter
// m.Groups[3].Value == Trust-Gi

这里的代码扩展了解释性注释:

Match m = Regex.Match(input, @"
    (\w+)           # one or more word characters; captured into group 1
    \s+             # one or more spaces
    (\w+)           # one or more word characters; captured into group 2
    \s+             # one or more spaces
    ""([\w-]+)""    # one or more word characters or dash, surrounded by double-quotes; captured into group 3
", RegexOptions.IgnorePatternWhitespace);

修改

Match m = Regex.Match(input, @"set vrouter ""([\w-]+)""");

然后路由器名称将在m.Groups[1].Value