The regex matches repeating groups spanning only one group

I want to match a string

6 cakes 5 donuts 12 muffins

      

into three groups, namely: 6 cakes

, 5 donuts

, 12 muffins

. For this I used a regex

([\d]{1}[\s]{1}[\w]*) 

      

But the problem is that it only matches the first group 6 cakes

and ignores the rest. How can I change it to repeat the group.

+3


source to share


1 answer


You just need to get the MatchCollection s Regex.Matches

and get the matches. The regex can be

\d+\s+\w+

      

See demo regex

In C #,

var str = "6 cakes 5 donuts 12 muffins";
var rx = new Regex(@"\d+\s+\w+");
var coll = rx.Matches(str);
foreach (Match m in coll)
    Console.WriteLine(m.Value);

      



See IDEONE demo

You can also use LINQ:

var str = "6 cakes 5 donuts 12 muffins";
var rx = new Regex(@"\d+\s+\w+");
var coll = rx.Matches(str).Cast<Match>().Select(p => p.Value).ToList();

      

enter image description here

+2


source







All Articles