遍历正则表达式匹配项

40

这是我的源字符串:

<box><3>
<table><1>
<chair><8>

这是我的正则表达式模式:

<(?<item>\w+?)><(?<count>\d+?)>

这是我的 Item 类

class Item
{
    string Name;
    int count;
    //(...)
}

这是我的物品收藏;

List<Item> OrderList = new List(Item);

我想根据源字符串填充列表中的项目。这是我的函数,但它不起作用。

Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled);
            foreach (Match ItemMatch in ItemRegex.Matches(sourceString))
            {
                Item temp = new Item(ItemMatch.Groups["item"].ToString(), int.Parse(ItemMatch.Groups["count"].ToString()));
                OrderList.Add(temp);
            }

这个例子可能会有一些小错误,比如缺少字母,因为这只是我在应用程序中的简化版本。

问题是最后我只有一个订单列表中的项目。

更新

我解决了它。 感谢帮助。


2
刚刚运行了它 - 像预期的那样工作(列表中有3个项)。 - ChrisWue
2
你能分享一下吗?如果有人遇到同样的问题,这可能会有所帮助。 - ChrisWue
1
@ChrisWue 这是我的应用程序代码中的错误。没有帮助。 - Hooch
一些关于理解和访问正则表达式匹配的代码可以在https://dev59.com/pF4c5IYBdhLWcg3w3dd_#27444808找到。 - AdrianHHH
2个回答

54
class Program
{
    static void Main(string[] args)
    {
        string sourceString = @"<box><3>
<table><1>
<chair><8>";
        Regex ItemRegex = new Regex(@"<(?<item>\w+?)><(?<count>\d+?)>", RegexOptions.Compiled);
        foreach (Match ItemMatch in ItemRegex.Matches(sourceString))
        {
            Console.WriteLine(ItemMatch);
        }

        Console.ReadLine();
    }
}

对我而言,返回了3个匹配项。你的问题必须在别处。


12

为了以后的参考,我想记录上面的代码转换为使用声明性方法的LinqPad代码片段:

var sourceString = @"<box><3>
<table><1>
<chair><8>";
var count = 0;
var ItemRegex = new Regex(@"<(?<item>[^>]+)><(?<count>[^>]*)>", RegexOptions.Compiled);
var OrderList = ItemRegex.Matches(sourceString)
                    .Cast<Match>()
                    .Select(m => new
                    {
                        Name = m.Groups["item"].ToString(),
                        Count = int.TryParse(m.Groups["count"].ToString(), out count) ? count : 0,
                    })
                    .ToList();
OrderList.Dump();

输出结果为:

匹配列表


那张截图上是什么程序?它是你自己的程序吗? - Hooch
1
这是由LinqPad的Dump()扩展方法生成的。您可以将Dump()附加到大多数对象的末尾,它将输出对象的格式化表示形式。 LinqPad只是编写/评估C#代码的杰出工具http://www.linqpad.net/。上述代码可以直接复制并粘贴到LinqPad中,它将生成表格。 - David Clarke
1
然后我就像,哈哈...我要点击“编辑”来查看制作这样漂亮的表格的Markdown。 - Suamere

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接