Regex for path name

Go To StackoverFlow.com

1

I want something that matches paths, such as those in a web URL without the domain name, or a Linux directory, something/like/this/and/allows-dashes

So in another word, the characters allowed are numbers, alphabets, dash, and slash. First and last character can't be dash nor slash.

Best I can get is this

^[a-z0-9]+[a-z0-9(\/)(-)]*[a-z0-9]+$

but it fails at

a/b-c/d
2012-04-04 03:24
by Andy
^[a-z0-9]+[a-z0-9/-]*[a-z0-9]+$ Why do you put a dash in parentheses - turbanoff 2012-04-04 03:27
You could also just use ^\w[\w\/\-]*\w$ . Of course this also means that your path must have at least 2 characters - gmalette 2012-04-04 03:32
Not allowing a forward slash at the beginning or end seems odd to me, as the former is always valid, and the latter is if you're path is a directory - Andrew Marshall 2012-04-04 03:40


2

You need to escape your - as well. Please try the following

^[a-z0-9]+[a-z0-9(\/)(\-)]*[a-z0-9]+$
2012-04-04 03:48
by Chetter Hummin
Ads