C# 正则表达式,用于匹配由任意数量的单词组成的任意长度的字符串,这些单词的最后一个单词始终是子单词(1到10之间的整数)

C# 正则表达式,用于匹配由任意数量的单词组成的任意长度的字符串,这些单词的最后一个单词始终是子单词(1到10之间的整数),c#,regex,C#,Regex,我正在寻找一个正则表达式,它允许我过滤由任意数量的单词组成的字符串列表,这些单词的最后一个字符必须小于或等于给定的整数。列表中每个目标字符串的最后一个字始终是子字符串。例如: List<string> attributes = new List<string> { "First Name of Child1", "Last Name of Child1", "Age of Child1", "Shipping Instruction

我正在寻找一个正则表达式,它允许我过滤由任意数量的单词组成的字符串列表,这些单词的最后一个字符必须小于或等于给定的整数。列表中每个目标字符串的最后一个字始终是子字符串。例如:

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",
}
试试这个:

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

});
int selected=2;
string exp=“Child(?\\d{1,2})$”;
正则表达式rg=新正则表达式(exp);
var result=属性。其中(a=>
{
int i;
字符串目标=rg.Match(a).Groups[“number”].Value;
如果(!int.TryParse(目标,输出i))
返回false;

回来(我可能最好使用RegEx和Linq的组合。使用RegEx,查找以数字结尾的任何字符串,并将其作为一个组返回。使用Linq,将该组转换为int并过滤掉任何大于目标整数的内容。您尝试了什么?这与
Child1
不匹配,只需更改
所选的
如果它与
Child2
不匹配,那么让我重新阅读这个问题,我可能误解了他们想要返回低于某个目标值的每个值。下面的答案应该有效。
var regex=new Regex(string.Join("|",Enumerable.Range(0,n).Select(i=>"Child"+i+"$")));
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);

});