Check string pattern in LINQ query

Viewed 460

In my c# code I have a list like this

public static List<string> Teachers_Group = new List<string>
{
    "-RO-ANSATTE",
    "-RO-GJESTEANSATTE"
};

I have a where clause in my linq query where I check

bool amITeacher = domainUser.Groups.Where(k => Helpers.Constants.Teachers_Group.Any(k.FullName.Contains)).Any();

Now I want to check that the string to check have a pattern like

XXX-RO-ANSATTE

Which means that I need to check that groupname has three alphabets as well. I think I need to use regex but I am not able to get started.

Any help?

3 Answers

I have changed your Linq Expression to use Regex

bool amITeacher = domainUser.Groups.Where(k => 
    Helpers.Constants.Teachers_Group.Any(t => 
        Regex.IsMatch(k, @"^[A-Za-z0-9]{3}\" + t + "$")))
    .Any();

Working Fiddle

If Regex is what you are looking for then you can have something like ^([A-Za-z]{3})-RO-.*

The following seems to answer all necessary conditions without false positives:

  bool amITeacher = domainUser.Groups.Where(k => Helpers.Constants.Teachers_Group.Any(x => Regex.IsMatch(x, "\\A[A-Z]{3}" + k))).Any();

Basically ensures that the input string is prefixed by exactly 3 capital english letters.

Related