遍历正则表达式匹配 [英] Looping through Regex Matches
本文介绍了遍历正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的源字符串:
<中> 3;>
<表>< 1>
<座椅>< 8'
这是我的正则表达式百通:
<(<项目> \ W +?)><(?< COUNT>?\ d +)>
这是我的Item类
类项目
{
字符串名称;
诠释计数;
//(...)
}
这是我的项目集合;
名单,其中,项目>订单系统=新名单(项目);
我想填充该列表基于源字符串项目的。 这是我的职责。它不工作。
正则表达式ItemRegex =新的正则表达式(@<?(小于项目> \ W +)><?(小于计数>?\ d +)>中, RegexOptions.Compiled);
的foreach(比赛ItemMatch在ItemRegex.Matches(sourceString))
{
项目临时=新的项目(ItemMatch.Groups [项]的ToString(),int.Parse(ItemMatch.Groups [伯爵]的ToString()));
OrderList.Add(临时);
}
Threre可能会像缺失的字母一些小失误就这个例子中,因为这是我在我的应用程序更简单的版本。
现在的问题是,到底我只有一个项目在订单系统。
更新
我得到它的工作。 Thans寻求帮助。
解决方案
类节目
{
静态无效的主要(字串[] args)
{
字符串sourceString = @<中> 3;>
<表>< 1>
<座椅>< 8>中;
正则表达式ItemRegex =新的正则表达式(@<(<项目> \ W +)><(< COUNT>?\ d +)>中,RegexOptions.Compiled);
的foreach(比赛ItemMatch在ItemRegex.Matches(sourceString))
{
Console.WriteLine(ItemMatch);
}
到Console.ReadLine();
}
}
返回3场比赛对我来说。你的问题一定在别处。
This is my source string:
<box><3>
<table><1>
<chair><8>
This is my Regex Patern:
<(?<item>\w+?)><(?<count>\d+?)>
This is my Item class
class Item
{
string Name;
int count;
//(...)
}
This is my Item Collection;
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.
The problem is that In the end I have only one Item in OrderList.
UPDATE
I got it working. Thans for help.
解决方案
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();
}
}
Returns 3 matches for me. Your problem must be elsewhere.
这篇关于遍历正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文