【问题标题】:Looping through Regex Matches循环通过正则表达式匹配
【发布时间】:2011-08-11 16:13:13
【问题描述】:

这是我的源字符串:

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

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

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

这是我的物品类

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);
            }

可能会出现一些小错误,例如在这个示例中缺少字母,因为这是我在应用程序中的更简单版本。

问题是最后我在 OrderList 中只有一个 Item。

更新

我让它工作了。 谢谢帮忙。

【问题讨论】:

  • 刚刚运行 - 工作正常(列表中的 3 项)。
  • 可以分享一下吗?如果有人遇到同样的问题,可能会有所帮助。
  • @ChrisWue 这是我的应用程序代码中的错误。没有帮助。
  • 一些关于理解和访问正则表达式匹配的代码可以在stackoverflow.com/a/27444808/546871找到

标签: c# .net regex foreach


【解决方案1】:
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 个匹配项。您的问题一定出在其他地方。

【讨论】:

    【解决方案2】:

    为了将来的参考,我想记录上面的代码转换为使用声明性方法作为 LinqPad 代码 sn-p:

    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();
    

    有输出:

    【讨论】:

    • 那张截图是什么程序?是你自己的程序吗?
    • 这是由 LinqPad 的 Dump() 扩展方法生成的。您可以将 Dump() 粘贴在大多数对象的末尾,它将输出对象的格式化表示。 LinqPad 只是一个用于编写/评估 C# 代码linqpad.net 的特殊工具。上面的代码可以直接复制粘贴到 LinqPad 中,生成表格。
    • 那我都喜欢,lawl...我要点击“编辑”来查看制作这么漂亮的表格的降价。
    猜你喜欢
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-11
    • 2021-10-24
    • 2020-03-20
    • 1970-01-01
    相关资源
    最近更新 更多