I currently have 100+ labels, with names like:
labelNumber1
labelNumber2
labelNumber3
labelNumber4
....
labelLetter1
labelLetter2
labelLetter3
labelLet
I know this is an old question, but I am here now, and:
Anyway, here is the code:
public List FindByPattern(string regexPattern)
where TControlType:Control
{
return Controls.OfType()
.Where(control => Regex.IsMatch(control.Name, regexPattern))
.ToList();
}
Usage:
//some regex samples you can test out
var startsWithLabel = $"^Label"; //Matches like .StartsWith()
var containsLabel = "Label"; //Matches like .Contains()
var startsWithLabelEndsWithNumber = "^Label.*\\d+&"; //matches Label8sdf12 and Label8
var containsLabelEndsWithNumber = "Label.*\\d+&"; //matches MyLabelRocks83475, MyLabel8Rocks54389, MyLabel8, Label8
var hasAnyNumber= "^CoolLabel\\d+$"; //matches CoolLabel437627
var labels = FindByPattern