Link to home
Start Free TrialLog in
Avatar of fischermx
fischermxFlag for Mexico

asked on

Regex to extract URL subdirectories.

Hi,

I'm trying to get a regex to extract subdirectories from, for example :
http://www.example.com/dir1/subdir1/page.aspx

I need to match just exactly "dir1" and "subdir1".
I think I have a problem with the "/" cause I have some time trying it without look.

Any help is appreciated.
Avatar of fischermx
fischermx
Flag of Mexico image

ASKER

Ok, let me tell you what I've got so far :

                  string myPath = "http://www.myexample.com/subdir1/subdir2/subdir3/";

                  string mapTo = myPath;
                  Regex regMap = new Regex(@"\/[a-zA-Z0-9]+\/",RegexOptions.IgnoreCase);
                  
                  foreach( Match matchExpr in regMap.Matches(mapTo) )
                  {
                        string expr = matchExpr.ToString();
                        Console.WriteLine('>'+expr);
                  }

This is outputing "subdir1" and "subdir3", somehow it skips "subdir2" !!
Why ?
SOLUTION
Avatar of Yurich
Yurich
Flag of New Zealand 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
and you don't have escape '/' char,                  
Regex myRegex = new Regex( "/[a-zA-Z0-9]+/",RegexOptions.IgnoreCase );

will do just fine

(but won't solve your problem) :(
try this:

Regex myRegex = new Regex( "/[a-zA-Z0-9][a-zA-Z0-9]+",RegexOptions.IgnoreCase );

it'll get all subdirs but it will get "www" as well but you can easily parse it later or think how to modify your regex to avoid it.

regards
Avatar of Bob Learned
Slight modification to skip //www:

"/[^/a-zA-Z0-9][a-zA-Z0-9]+"

   ^^^

Bob
hmm, for some reason

"/[^/a-zA-Z0-9][a-zA-Z0-9]+"

doesn't work for me - it doesn't find anything in the string (http://...) above.

isn't it a contradiction? we want it to have the first character '/' but not to start with '/'...

regards
ASKER CERTIFIED SOLUTION
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
this one works fine, should i accept the answer? ;)
I would if I were you :))  Actually, I'll split with you ;)

Bob