I am trying to pick paticular strings in an array and add them to a new array e.g. I want to grab all strings in the array that contain .txt and .rtf and add them to a new array e.g. filteredStrings[]
2 Answers
You do not need regex for something that simple: Contains works faster, and is easier to understand:
var filteredStrings = myStrings.Where(s => s.Contains(".txt") || s.Contains(".rtf")).ToArray();
If you insist on using regex, you can do this:
var regexp = new Regex("[.](txt|rtf)");
var filteredStrings = myStrings.Where(s => regexp.IsMatch(s)).ToArray();
6 Comments
mikus
however regex could be more flexible
tenfour
A plugin system would be more flexible; until you need that flexibility don't introduce the burden.
Till
Since they seem to be file extensions it might be a good idea to use the String.EndsWith() method.
Sergey Kalinichenko
@Till absolutely, if the OP is indeed talking about file extensions (which I am 99% certain that he does) then
EndsWith is a preferred choice.Mike
Error 1 'System.Array' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Array' could be found –
|
myArray.Where(x => Regex.IsMatch(x, @"\.(txt|rtf)$")).ToArray()
2 Comments
Mike
Error 1 'System.Array' does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Array' could be found
AlanT
@Mike What version of .Net are you using? If 3.5 or later you just need to add Using System.Linq to you file. If older, then is it possible for you to update to 3.5 or higher?