Reputation: 550
I'm trying to match the following pattern using C# and getting no match found
Regex
^([[a-z][A-Z]]*):([[a-z][A-Z][0-9],]*)$
Sample String
Student:Tom,Jerry
Whereas the same thing works in ruby(verified it using Rubular). Any idea why this is not working in c#?
Code Block
public static KeyValuePair<string, IList<string>> Parse(string s)
{
var pattern = new Regex(@"(\w*):([\w\d,]*)");
var matches = pattern.Matches(s);
if (matches.Count == 2)
{
return new KeyValuePair<string, IList<string>>(matches[0].Value, matches[1].Value.Split(','));
}
throw new System.FormatException();
}
Upvotes: 2
Views: 251
Reputation: 7088
You can simplify it even more:
^([A-z]*):([\w,]*)$
The first group is equivalent to [a-zA-Z]
and the second to [a-zA-Z0-9]
. If you want the first group to match digits along with characters, you can simply use \w
everywhere.
Upvotes: 1
Reputation: 9762
Try changing your regex slightly :-
([a-zA-Z]*):([a-zA-Z0-9,]*)
You could even simplify it a little further if you want all word characters (including underscore), if not then use the one above.
(\w*):([\w\d,]*)
There's no need to multi-group groupings such as [[a-z][A-Z]]
Upvotes: 9