I need to match element of the JSON array element in c# for filter autocomplete in c#. Here is my code:
string firstname = "h";
List<user> userlist = new List<user>();
user user1 = new user();
user1.firstname = "Hardik";
user1.lastname = "Gondalia";
userlist.Add(user1);
user user2 = new user();
user2.firstname = "John";
user2.lastname = "Abraham";
userlist.Add(user2);
user user3 = new user();
user3.firstname = "Will";
user3.lastname = "Smith";
userlist.Add(user3);
user user4 = new user();
user4.firstname = "Martin";
user4.lastname = "Luthor";
userlist.Add(user4);
var myRegex = new Regex(".*\\b" + firstname + "\\b.*");
var u = userlist.Where(i => myRegex.IsMatch(i.firstname)).ToList();
return Json(u, JsonRequestBehavior.AllowGet);
When I pass character "h" as firstname, I am getting count of u = 0; I am expecting user1 and user2 in variable u.
\bh\bwill only match the lone standinghbecause of the "word boundary"\b... Perhaps start by reading a regex tutorial.has a whole word. AndHardikcontains an uppercaseH(passRegexOptions.IgnoreCaseflag tomyRegex). Also,Regex.IsMatchalso finds partial matches, you do not need.*in your pattern at all. Judging by the code, you may achieve that without a regex, useuserlist.Where(i => culture.CompareInfo.IndexOf(i.firstname, firstname, CompareOptions.IgnoreCase) >= 0).ToList()(see stackoverflow.com/questions/444798/…)