Looping through Regex Matches

前端 未结 2 1332
一整个雨季
一整个雨季 2020-12-09 08:05

This is my source string:

<3>
<1>
<8>


This is my Regex Patern:

<(         


        
                      
相关标签:
2条回答
  • 2020-12-09 08:16

    For future reference I want to document the above code converted to using a declarative approach as a LinqPad code snippet:

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

    With output:

    List of matches

    0 讨论(0)
  • 2020-12-09 08:40
    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.

    0 讨论(0)
提交回复
热议问题