tags:

views:

31

answers:

1

I need to match the following strings and returns the values as groups:

abctic
abctac
xyztic
xyztac
ghhtic
ghhtac

Pattern is wrote with grouping is as follows:

(?<arch>[abc,xyz,ghh])(?<flavor>[tic,tac]$)

The above returns only parts of group names. (meaning match is not correct).

If I use * in each sub pattern instead of $ at the end, groups are correct, but that would mean that abcticff will also match.

Please let me know what my correct regex should be.

+1  A: 

Your pattern is incorrect because a pipe symbol | is used to specify alternate matches, not a comma in brackets as you were using, i.e., [x,y].

Your pattern should be: ^(?<arch>abc|xyz|ghh)(?<flavor>tic|tac)$ The ^ and $ metacharacters ensures the string matches from start to end. If you need to match text in a larger string you could replace them with \b to match on a word boundary.

Try this approach:

string[] inputs = { "abctic", "abctac", "xyztic", "xyztac", "ghhtic", "ghhtac" };
string pattern = @"^(?<arch>abc|xyz|ghh)(?<flavor>tic|tac)$";

foreach (var input in inputs)
{
    var match = Regex.Match(input, pattern);
    if (match.Success)
    {
        Console.WriteLine("Arch: {0} - Flavor: {1}",
                            match.Groups["arch"].Value,
                            match.Groups["flavor"].Value);
    }
    else
        Console.WriteLine("No match for: " + input);
}
Ahmad Mageed
Thanks very much Ahmad! I didnt realize I was using ,. Thanks again.