gandarez
gandarez

Reputation: 2662

Extract path without filename using regex?

I've exactly the string below. Using Regex how can I extract only the path?

"C:\Python34\py.exe" "%1" %*

I already tried these patterns unsuccessfully:

([a-zA-Z]:[\[a-zA-Z0-9 .]]*)

It gives me the whole path C:\Python34\py.exe

^[^ \t]+[ \t]+(.*)$

It gives me the whole string "C:\Python34\py.exe" "%1" %*

EDIT

I know the options from System.IO namespace. But there's a string coming and I need to extract the path from it-> "C:\Python34\py.exe" "%1" %* The string containing the path could be not regular as I showed.

Upvotes: 2

Views: 4184

Answers (4)

JNYRanger
JNYRanger

Reputation: 7097

Instead of using Regex you should use the static methods available in the System.IO.Path class.

If you want the path without the filename you can do this:

string myFullPath = @"C:\Python34\py.exe";
string pathOnly = Path.GetDirectoryName(myFullPath);
//pathOnly will be "C:\Python34"

EDIT: Since you're going to have arguments after the path we can first get the whatever is the first quoted substring:

Regex quotedPattern = new Regex("([\"'])(?:(?=(\\?))\2.)*?\1");
Match matches = quotedPattern.Match(myFullPath);
if(matches.Groups.Count > 0)
{
     pathOnly = matches.Captures[0].Value;
     pathOnly = Path.GetDirectoryName(pathOnly);
}

Regex Test: RegexStorm

Upvotes: 4

user557597
user557597

Reputation:

I guess you could generalize it to find just enough to distinguish it
from the other quoted values.

This requires at least a \ and file.ext in the quoted string.

 "
 # @"""([^""]*)\\([^""\\]+(?:\.[^"".\\]+))"""

 (                    # (1 start), Path
      [^"]* 
 )                    # (1 end)
 \\ 
 (                    # (2 start), File name
      [^"\\]+ 
      (?:
           \.
           [^".\\]+ 
      )
 )                    # (2 end)
 "

Output:

 **  Grp 0 -  ( pos 0 , len 22 ) 
"C:\Python34\py.exe.d"  
 **  Grp 1 -  ( pos 1 , len 11 ) 
C:\Python34  
 **  Grp 2 -  ( pos 13 , len 8 ) 
py.exe.d  

Upvotes: 0

Zohar Peled
Zohar Peled

Reputation: 82474

Another option is to use Path.GetDirectoryName and a simple Substring:

string value = "\"C:\\Python34\\py.exe\" \"%1\" %*";
string path = Path.GetDirectoryName(value.Substring(1, value.IndexOf("\"", 2)-1));

see fiddle here

Upvotes: 0

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32481

In your case using Path.GetDirectoryName on your input directly, throw exception. You may try this non-regex approach using combination of Split, Trim and GetDirectoryName:

string value = "\"C:\\Python34\\py.exe\" \"%1\" %*";

var result = System.IO.Path.GetDirectoryName(value.Split(' ').First().Trim('\"'));
//result: C:\Python34

Upvotes: 1

Related Questions