查找><之间的所有单词与正则表达式?

时间:2013-11-05 20:23:16

标签: c# xml regex

我有一个xml文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="name">word1</string>
<string name="namee">word2</string>
<string name="nameee">word3</string>

</resources>

我想找到&gt;之间的每个字&LT ;.因此word1,word2和word3。 我写了一些代码,但正则表达式只找到第一个单词(word1)。

    private void button1_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            StreamReader sr = new StreamReader(openFileDialog1.FileName);
            string s = sr.ReadToEnd();
            richTextBox1.Text = s;
        }

        string txt = richTextBox1.Text;
        string foundWords = Regex.Match(txt, @"\>(\w+)\<").Groups[1].Value;
        richTextBox1.Text = foundWords;

    }

我想找到&gt;之间的每个字&LT;并将其显示在富文本框中。

2 个答案:

答案 0 :(得分:2)

您应该考虑使用.NET中的其他内容解析XML。

说完了:

您只是因为您正在使用Match而获得第一个。 (匹配单个值) 请尝试使用匹配(返回可以迭代的匹配值的集合)。

尝试:

list<String> foundWords = new List<String>();
var foundMatches = regex.matches(txt, @"\>(\w+)<");
foreach(match m in foundMatches)
{
     foundWords.add(m.Groups[1].Value);
}
//do something with list of foundWords

答案 1 :(得分:1)

使用方法Regex.Matches()来捕获MatchCollection

private void button1_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        StreamReader sr = new StreamReader(openFileDialog1.FileName);
        string s = sr.ReadToEnd();
        richTextBox1.Text = s;
    }

    string txt = richTextBox1.Text;
    var foundWords = Regex.Matches(txt, @"(?<=>)(\w+?)(?=<)");
    richTextBox1.Text = string.Join("\n", foundWords.Cast<Match>().Select(x=>x.Value).ToArray());
}