views:

731

answers:

3

I can't seem to find a Regular Expression for javascript that will test for the following cases:

  • c:\temp
  • D:\directoryname\testing\
  • \john-desktop\tempdir\

You can see what I'm going for. I just need it to validate a file path. But it seems like all the expressions I've found, don't work for javascript.

Thank you in advance.

John

+1  A: 

Try this:

([a-zA-Z]:)?(\\[a-zA-Z0-9_-]+)+\\?

EDIT:

@Bart made me think about this regexp. This one should work nice for windows' paths.

^([a-zA-Z]:)?(\\[^<>:"/\\|?*]+)+\\?$
Gaim
That matches an empty string as well. Also note that folders in Windows can have more than the set `[a-zA-Z0-9_-]` in them.
Bart Kiers
+1 because I feel better when I see somebody else which writes regexs like mines; I'm "normal" after all
Rubens Farias
@Bart You are right, thanks. I'll fix it. Note: I know but it is simply editable. I wrote base regex - idea is clear
Gaim
A: 

You could start with:

^([a-zA-Z]:)?(\\[a-zA-Z0-9_\-]+)+\\?

This matches all your samples.

Rubens Farias
A: 

I think this will work:

var reg = new RegExp("^(?>[a-z]:)?(?>\\|/)?([^\\/?%*:|\"<>\r\n]+(?>\\|/)?)+$", "i");

I've just excluded all(?) invalid characters in filenames. Should work with international filenames (I dunno) as well as any OS path type (with the exceptions noted below).

Kevin Peno
Sorry but some of your excluded chars are allowed, for example `% [ ]`
Gaim
% was defined on the wiki page I linked as a wildcard on one system, thus, for compatability, it was not allowed. I've updated to remove [] from the disallow list though.
Kevin Peno
@Kevin I am using Linux Ubuntu ( Jaunty ) and % there is allowed character. So I can have a file which doesn't match your regexp ( I know, usage of there characters is ugly but we don't know nothing about future customers )
Gaim
Like I said, it's not globally valid per the wiki page, so I added it to the rule list. If the character in question does not matter in your risk assessment, remove it :) See: http://en.wikipedia.org/wiki/Filename
Kevin Peno