循环通过正则表达式匹配 [英] Looping through Regex Matches

查看:41
本文介绍了循环通过正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的源字符串:

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

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

This is my Regex Patern:

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

这是我的物品类

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

这是我的物品收藏;

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

我想用基于源字符串的项目填充该列表.这是我的职能.它不起作用.

I want to populate that list with Item's based on source string. This is my function. It's not working.

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

可能存在一些小错误,例如在此示例中遗漏了字母,因为这是我应用程序中更简单的版本.

Threre might be some small mistakes like missing letter it this example because this is easier version of what I have in my app.

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

The problem is that In the end I have only one Item in OrderList.

更新

我成功了.感谢帮助.

推荐答案

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 个匹配项.你的问题一定在别处.

Returns 3 matches for me. Your problem must be elsewhere.

这篇关于循环通过正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆