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
Here's something I came up with:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string s = @"Hello John these are the files you have to send us today:
C:\projects\orders20101130.docx also we would like you to send
C:\some\file.txt, C:\someother.file and d:\some file\with spaces.ext
Thank you";
Extract(s);
}
private static readonly Regex rx = new Regex
(@"[a-z]:\\(?:[^\\:]+\\)*((?:[^:\\]+)\.\w+)", RegexOptions.IgnoreCase);
static void Extract(string text)
{
MatchCollection matches = rx.Matches(text);
foreach (Match match in matches)
{
Console.WriteLine("'{0}'", match.Value);
}
}
}
Produces: (see on ideone)
'C:\projects\orders20101130.docx', file: 'orders20101130.docx'
'C:\some\file.txt', file: 'file.txt'
'C:\someother.file', file: 'someother.file'
'd:\some file\with spaces.ext', file: 'with spaces.ext'
The regex is not extremely robust (it does make a few assumptions) but it worked for your examples as well.
Here is a version of the program if you use
tags. Change the regex and Extract
to:
private static readonly Regex rx = new Regex
(@"(.+?) ", RegexOptions.IgnoreCase);
static void Extract(string text)
{
MatchCollection matches = rx.Matches(text);
foreach (Match match in matches)
{
Console.WriteLine("'{0}'", match.Groups[1]);
}
}
Also available on ideone.