-3

I am looking for a regular expression that would allow me filter a list of strings made of an arbitrary number of words whose last character of the last word must be less than or equal to a given integer. The last word of each of the target strings in the list is always Child<1 to 10>. For example:

List<string> attributes = new List<string>
{
     "First Name of Child1",
     "Last Name of Child1",
     "Age of Child1",
     "Shipping Instructions",
     "First Name of Child2",
     "Last Name of Child2",
     "Age of Child2",
     "Non-Profit Name",
     "First Name of Child3",
     "Last Name of Child3",
     "Age of Child3",
}

If the target integer is 2, the filtered list would contain:

 "First Name of Child1",
 "Last Name of Child1",
 "Age of Child1",
 "First Name of Child2",
 "Last Name of Child2",
 "Age of Child2"
  • Might be best to use a combination of RegEx and Linq for this. With RegEx, look for any string that ends with numeric digits and return those as a group. With Linq, convert that group to an int and filter out anything greater than your target integer. – Mike Christensen Oct 19 '15 at 22:20
  • And what have you tried? – CodeCaster Oct 19 '15 at 22:20

2 Answers2

1
var regex=new Regex(string.Join("|",Enumerable.Range(0,n).Select(i=>"Child"+i+"$")));
Blindy
  • 65,249
  • 10
  • 91
  • 131
0

Try this:

int selected = 2;
string exp = "Child(?<number>\\d{1,2})$";
Regex rg = new Regex(exp);

var result = attributes.Where(a =>
{
    int i;
    string target = rg.Match(a).Groups["number"].Value;
    if (!int.TryParse(target, out i))
        return false;
    return (i <= selected);

});

Code edited because of my poor understanding of regular expression numeric "range" handling.

Luc Morin
  • 5,302
  • 20
  • 39