简体   繁体   English

正则表达式检查以查找具有给定字符的项目

[英]Regex to check to find out items with given character

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 我创建了MyClass类型的列表,并添加了一些项目

    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. 我想用linq或regex来做,也欢迎其他好的选择。 I tried using contains method but got all items having * . 我尝试使用contains方法,但所有项目都带有*

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

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();

If you only need single stars I suspect those shouldn't contain at least 2 stars. 如果您只需要单颗星,我怀疑这些星不应该包含至少两颗星。 If stars might show up elsewhere a regex might be better. 如果星星可能出现在其他地方,则正则表达式可能会更好。

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

var doublestar = lst.Where(x => (x.Name.Contains("**") and !(x.Name.Contains("***")))).ToList();

Or with Regex 或使用正则表达式

Regex rgx1 = new Regex(@"^[^*]*\\*[^*]*$");
Regex rgx2 = new Regex(@"^[^*]*\\*\\*[^*]*$");
var singlestar = lst.Where(x => rgx1.IsMatch(x.Name)).ToList();

var doublestar = lst.Where(x => rgx2.IsMatch(x.Name)).ToList();

With the Regex, there should be no other stars anywhere else in the name. 使用Regex,名称中的其他任何地方都不应有其他星星。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM