1

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.

8
  • 2
    "I am expecting user1 and user2" - why? \bh\b will only match the lone standing h because of the "word boundary" \b... Perhaps start by reading a regex tutorial. Commented Aug 3, 2016 at 10:11
  • 3
    Well, these first names do not contain h as a whole word. And Hardik contains an uppercase H (pass RegexOptions.IgnoreCase flag to myRegex). Also, 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() (see stackoverflow.com/questions/444798/…) Commented Aug 3, 2016 at 10:12
  • @CodeCaster : you mean to say that \b will match whole word rather then individual character? Commented Aug 3, 2016 at 10:14
  • Why do you even need regular expressions here Commented Aug 3, 2016 at 10:16
  • @zerkms : I thought regex was good alternative. Any other approach is most welcome. Commented Aug 3, 2016 at 10:18

1 Answer 1

1

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 a first name as a whole word.

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.