maria Lynx
maria Lynx

Reputation: 59

c# Regex several numbers with comma

I would like to know how to get more than one comma with regex
I started with the string:

var str = "A:12,18,12 B:10";

now started with regex:

var reg = Regex.Matches(str,@"A:(\d+)\sB:(\d+)").cast<Match>().select(rg => new {
 A = rg.Groups[1].Value,
 B = rg.Groups[2].Value
}).ToList();
 foreach(var lop in reg)
 { 
   Console.Write(lop.A + "-" + lop.B);
 }

I am not good in regex but in B: everything works fine, in A: but not. I think it's the comma Thank you!

Upvotes: 1

Views: 52

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112352

Change the regex to

@"A:(\d+(,\d+)*)\sB:(\d+)

i.e., add zero or more repetitions (*) of ,\d+.

If commas can appear in B as well:

@"A:(\d+(,\d+)*)\sB:(\d+(,\d+)*)

Upvotes: 1

Related Questions