4

Here is the post which describes the way to create an Expression<Func<MyClass, bool>> predicate dynamically. Here is a snippet:

 var param = Expression.Parameter(typeof(string), "p");
    var len = Expression.PropertyOrField(param, "SomeText");
    var body = Expression.Equal(
        len, Expression.Constant("Text"));

    var lambda = Expression.Lambda<Func<string, bool>>(
        body, param);

I wonder how do I apply a regexp to a string instead of Equality. Is there a possibility? A possible pseudo code would be like:

 var param = Expression.Parameter(typeof(string), "p");
    var len = Expression.PropertyOrField(param, "SomeText");
    var body = Expression.Regexp(
        len, @"\D+");

    var lambda = Expression.Lambda<Func<string, bool>>(
        body, param);
Community
  • 1
  • 1
Yurii Hohan
  • 4,021
  • 4
  • 40
  • 54

1 Answers1

2

You can use Expression.Call(Type type, string methodName, Type[] typeArguments, params Expression[] arguments) to call your test method that checks for regular expression.

 List<string> lista = new List<string>() { "aaaa", "aaabb", "aaacccc", "eee" };

        var param = Expression.Parameter(typeof(string), "s");
        var pattern = Expression.Constant("\\Aa");

        var test = Expression.Call(typeof(Regex), "IsMatch", null, param, pattern);

        var lambda = Expression.Lambda<Func<string, bool>>(test, param);

        IEnumerable<string> query = lista.Where(lambda.Compile());

        foreach (string s in query) 
        {
            Console.WriteLine(s);
        }
Massimo Zerbini
  • 3,125
  • 22
  • 22
  • Where does this string come from - "IsMatch"? – Yurii Hohan Sep 27 '11 at 11:21
  • Suppose you have the following structure var data = new List { new TestClass {Name = "valvoline", Quantity = 3}, new TestClass {Name = "castrol", Quantity = 3}, new TestClass {Name = "valve", Quantity = 1}, }; and you want to search with the next criteria var queryItems = new List { new QueryItem {Caption = "Name", Value = "v*", Separator = NextItem.Last}; – Yurii Hohan Sep 27 '11 at 11:31
  • @Hohhi isMatch is a method of Regex. In your original question you ask about regular expression checks. – Massimo Zerbini Sep 27 '11 at 12:15
  • how to do regex replace in this example. – Tun Aug 20 '13 at 09:35