DaniKR
DaniKR

Reputation: 2448

Substring from path string

In strings like this (I get strings from Directory.GetFiles())

string temp = "\\folder_name\\file_name.filetype.[somename@somedomain].wallet"

What is the best way to substring: file_name.filetype

I could do something like this:

const string source = ".[somename@somedomain].wallet";
temp.Substring(0, temp.IndexOf(source, StringComparison.Ordinal));

... but problem is that "mail" in string ".[xxxx@xxxx].wallet" is changing, in my words my string source should be something like this:

const string source = ".[*].wallet"; //so all strings that are in .[all_strings].wallet

Is there an easy way to do something like this (with asterisk "*"), or I will have to substring piece by piece and concatenate this new string?

Upvotes: 2

Views: 520

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You can construct a regex that requires a backslash before the substring of interest, and a text in square brackets followed by .wallet at the end.

Here is how you can do with in C# regex APIs:

string temp = @"\folder_name\file_name.filetype.[somename@somedomain].wallet";
var m = Regex.Match(temp, @"(?<=\\)[^.]*\.[^.]*(?=\.\[[^\]]*\].wallet)");
if (m.Success) {
    Console.WriteLine(m.Value);
} else {
    Console.WriteLine("<no match>");
}

Demo.

(?<=...) and (?=...) constructs are zero-length look-ahead and look-behind. They are not included in the m.Value.

Upvotes: 2

NtFreX
NtFreX

Reputation: 11357

You could also use an regex to achieve this. The first group of the following one should be what you are looking for.

string temp = "\\folder_name\\file_name.filetype.[somename@somedomain].wallet";

var filenameRegex = new Regex("^.*\\\\(.*)\\.\\[.*\\]\\.wallet$");
var match = filenameRegex.Match(temp);

var result = match.Groups[1];

Upvotes: 0

Igor
Igor

Reputation: 62213

You could search for the 2nd index of . and take everything before that point.

string temp = "\\folder_name\\file_name.filetype.[somename@somedomain].wallet";

var filename = Path.GetFileName(temp);
var lastIndex = filename.IndexOf('.', filename.IndexOf('.') + 1);
var fileYouAreLookingFor = filename.Substring(0, lastIndex);

Working fiddle

Upvotes: 0

Related Questions