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();
LVL 1
GorGor1Asked:
Who is Participating?
 
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
 
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
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.