Splitting a file name with multiple delimiters

Viewed 329

How would I split this file name. image-1.png-ad-en-Km-Image.txt so that the end result looks like this. (also to ignore the '.txt' at the end).

  • image-1.png
  • ad
  • en
  • Km
  • Image

In other words I want to ignore the first hyphen (-). The first 'segment' will always end with .png or .jpg.

I would usually do it something like this but that first hyphen in the image name is throwing a bit of a spanner in the works.

 var endOfName = name.LastIndexOf(".txt");
 var names = name.Substring(0, endOfName).Split('-');
2 Answers

It seems, that you are working with files' names, that's why I suggest using Path class to manipulate with names and extensions:

  using System.IO;

  .. 

  string source = "image-1.png-ad-en-Km-Image.txt";

  // get rid of ".txt"
  string name = Path.GetFileNameWithoutExtension(source);

  // split extension ".png-ad-en-Km-Image" into {".png", "ad", "en", "Km", "Image"}
  string[] items = Path.GetExtension(name).Split('-');

  // Add file name "image-1" to the 1st item
  items[0] = Path.GetFileNameWithoutExtension(name) + items[0];

Let's have a look:

  Console.WriteLine(string.Join(Environment.NewLine, items));

Outcome:

image-1.png
ad
en
Km
Image

Please, note, that even for elaborated files' names like

string source = "my.image-1-2-3.png-ad-en-Km-Image.txt";

we'll have

my.image-1-2-3.png # <- valid file name
ad
en
Km
Image 

If the pattern of the filename is constant, you can use the following function:

static List<string> GetNames(string filename)
{
    var segments = filename.Split('.');

    // The second segment contains all the "-" delimited tokens
    // including the extension of the first segment (png/jpg)
    var others = segments[1].Split('-');

    var firstName = $"{segments[0]}.{others.First()}";

    var names = new List<string> { firstName };

    // Add all but the first element, since it's part of firstName
    names.AddRange(others.Skip(1));

    // If you wanted to add the final ".txt", you'd simply:
    // names.Add($".{segments[2]}");

    return names;
}

static void Main()
{
    var filename = "image-1.png-ad-en-Km-Image.txt";
    var names = GetNames(filename); // image-1.png, ad, en, Km, Image
}
Related