Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex is not matching in c#

Tags:

c#

.net

regex

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();
    }
like image 901
Krishnaswamy Subramanian Avatar asked Feb 03 '26 12:02

Krishnaswamy Subramanian


1 Answers

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]]

like image 170
John Mitchell Avatar answered Feb 05 '26 00:02

John Mitchell