Regex Matches not working as excepted
I'm trying to group the following string into three groups.
0:0:Awesome:awesome
That being "0", "0" and "Awesome:awesome"
Using this regular expression:
^([0-9]+)\:([0-9]*)\:(.*)$
It works fine on online regex services: http://rubular.com/r/QePxt57EwU
But it seems like .NET doesn't agree. Picture of Regex problem from Visual Studio http://xs.to/image-开发者_如何学编程3F8A_4BA916BD.jpg
The MatchCollection
contains the results of applying the regular expression to the source string iteratively. In your case there is only 1 match - so the results are correct. What you have are multiple captures within the match. This is what you want to compare against - not the number of matches.
MatchCollection matches = RegEx.Matches("0:0:Awesome:awesome",
"^([0-9]+)\:([0-9]*)\:(.*)$");
if( matches.Count != 1 && matches[0].Captures.Count != 3 )
//...
When you want to access the matched groups the following could help you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var pattern = "^([0-9]+)\\:([0-9]*)\\:(.*)$";
var matches = Regex.Match("0:0:Awesome:awesome", pattern);
foreach (var match in matches.Groups)
Console.WriteLine(match);
}
}
}
I think this regexp would suit
(?<nums>\d+\:?)+(?<rest>.*)
Then you can get the groupings for 'num' and 'rest' together as shown
public Regex MyRegex = new Regex( "^(?<nums>\\d+\\:?)+(?<rest>.*)$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); MatchCollection ms = MyRegex.Matches(InputText);
Where InputText
would contain the sample '0:0:Awesome:Awesome'
精彩评论