Reputation: 2724
I have the ability to search and return files in a given file location. I also have the ability to return a number sequence from the file name as such:
public List<AvailableFile> GetAvailableFiles(string rootFolder)
{
List<AvailableFile> files = new List<AvailableFile>();
if (Directory.Exists(rootFolder))
{
Log.Info("Checking folder: " + rootFolder + " for files");
try
{
foreach (string f in Directory.GetFiles(rootFolder))
{
files = FileUpload.CreateFileList(f);
var getNumbers = new String(f.Where(Char.IsDigit).ToArray());
System.Diagnostics.Debug.WriteLine(getNumbers);
}
}
catch (System.Exception excpt)
{
Log.Fatal("GetAvailableFiles failed: " + excpt.Message);
}
}
return files;
}
What I want to do now is only return a sequence of numbers that is exactly 8 characters long. For example a file with the name New File1 12345678 123
I'm only caring about getting 12345678
back.
How can I modify my method to achieve this?
Upvotes: 0
Views: 1479
Reputation: 191
You could use a regular expression:
var match = Regex.Match(input, @"\d{8}");
Upvotes: 1
Reputation: 37000
A regex seems to be good for this:
var r = new Regex(".*(\\d{8})");
foreach (string f in Directory.GetFiles(rootFolder))
{
files = FileUpload.CreateFileList(f);
var match = r.Match(f);
if(m.Success)
{
Console.WriteLine(m.Groups[1]); // be aware that index zero contains the entire matched string
}
}
The regex will match the very first occurence of 8 digits and put it into the GroupsCollection
.
Upvotes: 3