2

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[]

1
  • Do you HAVE to use regex? Would be much simpler to simply use String.Contains Commented Jan 31, 2012 at 14:21

2 Answers 2

7

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();
Sign up to request clarification or add additional context in comments.

6 Comments

however regex could be more flexible
A plugin system would be more flexible; until you need that flexibility don't introduce the burden.
Since they seem to be file extensions it might be a good idea to use the String.EndsWith() method.
@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.
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 –
|
1
myArray.Where(x => Regex.IsMatch(x, @"\.(txt|rtf)$")).ToArray()

2 Comments

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
@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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.