开发者

splitting a filename - substring?

I have the following filename:

SCO_InsBooking_1.pdf

SCO_InsBooking_10.pdf

SCO_InsBooking_100.p开发者_Go百科df

SCO_InsBooking_1000.pdf

I an reading the file name using FileInfo and want to split it so I only get the 1, 10, 100 or 1000 number how would I achive this?


Using regular expressions:

string number = Regex.Match("SCO_InsBooking_1000.pdf", @"\d+").Value;

Assuming that no other number is present in the file name.


filename = filename.Substring(filename.lastIndexOf("_")+1);
filename = filename.Substring(0, filename.indexOf("."));

Alternatively

filename = Regex.Replace(filename, "_(\d+).pdf$", "$1");


string number = "SCO_InsBooking_1.pdf".split('_')[2].split('.')[0];

Of course, it would be better with some bounds checking to avoid index exceptions.


You can do this with a regular expression:

Regex.Match(filename, @".*_(\d+).pdf").Groups[1].Value


You could use string.replace()

using System.Collections.Generic;

namespace strings1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names = new List<string> { 
                "SCO_InsBooking_1.pdf", 
                "SCO_InsBooking_10.pdf", 
                "SCO_InsBooking_100.pdf", 
                "SCO_InsBooking_1000.pdf" };

            List<string> numbers = new List<string>();
            foreach (string item in names)
            {
                numbers.Add(item.Replace("SCO_InsBooking_", string.Empty).Replace(".pdf",string.Empty));
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜