Ubiquitous Developers Ubiquitous Developers - 1 year ago 194
JSON Question

Regex to Match Json array element in C#

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";

user user2 = new user();
user2.firstname = "John";
user2.lastname = "Abraham";

user user3 = new user();
user3.firstname = "Will";
user3.lastname = "Smith";

user user4 = new user();
user4.firstname = "Martin";
user4.lastname = "Luthor";

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.

Answer Source

I am posting an answer since there are several issues here.

First, these first names do not contain h as a whole word and you defined \b in your pattern to match firstname as a whole word. Check word boundary topic.

Second, Hardik contains an uppercase H (so, you should consider passing RegexOptions.IgnoreCase flag to myRegex).

Third, Regex.IsMatch also finds partial matches, you do not need .* in your pattern at all.

Judging by the code, you may achieve that without a regex, use

userlist.Where(i => culture.CompareInfo.IndexOf(i.firstname, firstname, CompareOptions.IgnoreCase) >= 0).ToList()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download