0

Question for any RegEx masters out there who have a minute to help me out... I have an application which allows users to specify a filename which is used to grab files off of an ftp or local directory... In the filename, they are allowed to specify wildcards using the * character...

Examples include:

file1*.txt, *.* , acb*.* , file.txt , *abc*.xml , filewithnoext*

I need a dynamic regular expression to filter my file list and only retrieve files based on the users input... Can anyone out there help me with this? Thanks for taking the time to take a look.

Franco Trombetta
  • 207
  • 1
  • 5
  • 14
  • Do you want to retrieve file name without extension? –  Nov 27 '13 at 14:45
  • yes if no "." is present in the user input text – Franco Trombetta Nov 27 '13 at 14:46
  • 1
    Can you show us the code used to retrieve the files? Perhaps the input by the user, including the wildcards, could be used by the function retrieving the files... – Pantelis Natsiavas Nov 27 '13 at 14:48
  • 1
    [This Answer](http://stackoverflow.com/questions/8443524/using-directory-getfiles-with-a-regex-in-c) is very close to what you want – Jonesopolis Nov 27 '13 at 14:48
  • The wildcard is essentially an subset of Regular Expressions, you can just take their string, escape special characters like `.` and replace the wild card with a .*? which will match anything 0 or more times but as few as possible – T. Kiley Nov 27 '13 at 14:49
  • currently, they specify the filepath and I take that to construct the Regular expression... I have: Regex regexFilter = new Regex( "^" + Regex.Escape(Path.GetFileName(strLocaFilePath)).Replace(@"\*", ".*"). Replace(@"\?", ".") + "$", RegexOptions.IgnoreCase); But this is incomplete. I need it to work for examples like (wildcard).(wildcard) – Franco Trombetta Nov 27 '13 at 14:53

1 Answers1

2

You could try something like this:

string reg = Regex.Escape(userinput).Replace(@"\*", ".*?");

Then iterate through each file and check them by doing something like this:

foreach (string file in files)
{
    if(!Regex.Match(file + "$", reg).Success)
        continue;

    //...
}
Prime
  • 2,410
  • 1
  • 20
  • 35
  • The input can also contain a `.` so you need to replace that too – T. Kiley Nov 27 '13 at 14:51
  • @T.Kiley It'll be escaped via `Regex.Escape()` – Prime Nov 27 '13 at 14:52
  • 1
    @FrancoTrombetta it should, *.* would turn into a Regex match for `.*?\..*?` but you should definitely look at Jonesy's comment on the OP which has a link to here: http://stackoverflow.com/questions/8443524/using-directory-getfiles-with-a-regex-in-c – Prime Nov 27 '13 at 15:07
  • 1
    You'll want to add `$` to the end of the regex. Otherwise "*.xml" will match "myfile.xml.txt" and "myfile.xmltest". – Jim Mischel Nov 27 '13 at 16:18