Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1861
  • Last Modified:

Regex...extract filename

I always think I understand regex's until I go to use them. I'm using C# and .NET Framework.   Let's say I have the following string:

"C:\\MsDev\\Sharp\\bin\\Debug\\Control.dll`~`3`~`0`~`"    notice that `~` is my delimiter

I want to extract the filename from the string using regex.

I think the following snippet should work, but it is assigning 'filename' with the entire string, not just the filename.  Any ideas??  Thanks in advance.

//Get the filename from string using regex...
string filename = (Regex.Replace(dataString, "^(.*)(`~`)?", "$1")).ToString();
0
GorGor1
Asked:
GorGor1
  • 3
  • 3
  • 2
1 Solution
 
msdixonCommented:
System.IO.Path.GetFileName(file); // where file is the full path and file name
0
 
GorGor1Author Commented:
How does that work??  How is that going to extract the filename from my `~` delimited string??
0
 
TheAvengerCommented:
Is it obligatory to use regex? You can use this:

int delPos = dataString.IndexOf ("'~'");
string filename = dataString.Substring (0, delPos);
filename = filename.Substring (filename.LastIndexOf ("\\") + 1);
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
GorGor1Author Commented:
I'd much rather use regex.  The string is actually much much longer than what I posted here and I'm using regex to remove and read elements of the string, etc.

Long story short, using Regex.Replace(...) makes the most sense in my particular case.
0
 
TheAvengerCommented:
OK, this one works in your case:

string dataString = "C:\\MsDev\\Sharp\\bin\\Debug\\Control.dll'~'3'~'0'~'";
string pattern = "(?:[\\w\\\\:]*)(?:\\\\)([^\\\\']*).*";
string filename = (Regex.Replace(dataString, pattern, "$1")).ToString();
MessageBox.Show (filename);
0
 
GorGor1Author Commented:
Thanks, it works great!  Turns out that I like your other solution better.  It's definitely a much cleaner approach.  Thanks again.
0
 
msdixonCommented:
so how is that any easier than using the Path.GetFileName method? it seems like a lot more work to me.
0
 
TheAvengerCommented:
He has the file path in a string variable among other data and wants to extract it. Path.GetFileName will give you the path of a pysically existing file which is absolutely different
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now