0

我有一个 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>

我想找到> <之间的每个单词。因此 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;

    }

我想找到 > < 之间的每个单词并将其显示在富文本框中。

4

2 回答 2

2

您可能应该考虑使用其他融入 .NET 的东西来解析 XML。

话说回来:

您只得到第一个,因为您使用的是 Match。(匹配单个值)尝试改用 Matches(返回可以迭代的 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
于 2013-11-05T20:25:56.057 回答
1

use method Regex.Matches() to capture 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());
}
于 2013-11-05T20:26:11.807 回答