A way to use RegEx to find a set of filenames paths in a string

后端 未结 3 1160
长情又很酷
长情又很酷 2021-02-09 18:12

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

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 18:52

    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.

提交回复
热议问题