Link to home
Start Free TrialLog in
Avatar of GorGor1
GorGor1

asked on

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();
Avatar of msdixon
msdixon

System.IO.Path.GetFileName(file); // where file is the full path and file name
Avatar of GorGor1

ASKER

How does that work??  How is that going to extract the filename from my `~` delimited string??
ASKER CERTIFIED SOLUTION
Avatar of TheAvenger
TheAvenger
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of GorGor1

ASKER

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.
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);
Avatar of GorGor1

ASKER

Thanks, it works great!  Turns out that I like your other solution better.  It's definitely a much cleaner approach.  Thanks again.
so how is that any easier than using the Path.GetFileName method? it seems like a lot more work to me.
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