Home > DeveloperSection > Forums > How to regex to check to find out items with given character?
marcel ethan
marcel ethan

Total Post:105

Points:735
Posted on    January-27-2015 10:12 PM

 ASP.Net C#  ASP.NET MVC  Regex 
Ratings:


 1 Reply(s)
 448  View(s)
Rate this:

I've a class

public class MyClass

        {

            public MyClass(int id, string name)

            {

                this.Id = id;

                //Id = id;

                this.Name = name;

            }

            public int Id { get; set; }

            public string Name { get; set; }

        }

I created a list of MyClass type and added few items to it

    List<MyClass> lst = new List<MyClass>();

    lst.Add(new MyClass(1, "Name1"));

    lst.Add(new MyClass(2, "ab****cdefg"));

    lst.Add(new MyClass(3, "he*llo"));

    lst.Add(new MyClass(4, "pa**yed"));

    lst.Add(new MyClass(5, "Names2"));

    lst.Add(new MyClass(6, "hi******iiii"));

    lst.Add(new MyClass(7, "so*me"));

    lst.Add(new MyClass(8, "so**rt"));

    lst.Add(new MyClass(9, "*"));

    lst.Add(new MyClass(10, "**"));

    lst.Add(new MyClass(11, "t*e*s*t"));

    lst.Add(new MyClass(12, "t**e**s**t"));

How can i find items having only one * in name field in a list and two ** in name field in another list. I'ld like to do it by linq or regex, any other good option is also invited. I tried using containsmethod but got all items having *.

var singlestar = lst.Where(x => x.Name.Contains("*")).ToList();



Samuel Fernandes
Samuel Fernandes

Total Post:156

Points:1096
Posted on    January-27-2015 10:37 PM

this should match names with just one "\*" and two "\*\*"

var singlestar = lst.Where(x =>Regex.Matches(x.Name,  "\\*").Count == 1).ToList();

var twostar = lst.Where(x =>Regex.Matches(x.Name,  "\\*\\*").Count == 1).ToList();


Don't want to miss updates? Please click the below button!

Follow MindStick