Good morning guys
Is there a good way to use regular expression in C# in order to find all filenames and their paths within a string
variable?
For e
If you put some constraints on your filename requirements, you can use code similar to this:
string s = @"Hello John
these are the files you have to send us today: C:\Development\Projects 2010\Accounting\file20101130.csv, C:\Development\Projects 2010\Accounting\orders20101130.docx
also we would like you to send C:\Development\Projects 2010\Accounting\customersupdated.xls
thank you";
Regex regexObj = new Regex(@"\b[a-z]:\\(?:[^<>:""/\\|?*\n\r\0-\37]+\\)*[^<>:""/\\|?*\n\r\0-\37]+\.[a-z0-9\.]{1,5}", RegexOptions.IgnorePatternWhitespace|RegexOptions.IgnoreCase);
MatchCollection fileNameMatchCollection = regexObj.Matches(s);
foreach (Match fileNameMatch in fileNameMatchCollection)
{
MessageBox.Show(fileNameMatch.Value);
}
In this case, I limited extensions to a length of 1-5 characters. You can obviously use another value or restrict the characters allowed in filename extensions further. The list of valid characters is taken from the MSDN article Naming Files, Paths, and Namespaces.