简体   繁体   中英

C# Check string for specific length of numbers

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?

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 .

您可以使用正则表达式:

var match = Regex.Match(input, @"\d{8}");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM