views:

55

answers:

2
 I have been doing some searching for a regex that can be used as a rule to disallow users entering windows file paths without escaping the "\".  So far I have found this expression  

[^\\]*$

However, this fails for the following:

C:\\Program Files\\testing

By fails I mean that it does not validate this string. Any help would be greatly appreciated, and yes I am bound to using regex.

+4  A: 
^(\\\\|[^\\])*$

will match strings that only contain escaped \ characters or non-\ characters. (For a little extra performance, you could improve it to: ^(?:\\\\|[^\\]+)*$)

In Perl:

if ($subject =~ m/^(?:\\\\|[^\\]+)*$/) {
    # Successful match
} else {
    # Match attempt failed
}

This will match

C:\\Program Files\\test
abcd
h983475iuh 87435v z 87tr8v74
\\\\\\\\\\

and fail

C:\Program Files\test
\
\\\

etc.

Tim Pietzcker
this does not function accordingly on my system
Woot4Moo
If I pass "C:\Program Files\testing" it accepts it, this is not what I am anticipating
Woot4Moo
Try passing 'C:\Program Files\testing' (using single quotes instead of double quotes). Inside double quotes, backslash is an escape character; inside single quotes it isn't.
Thom Boyer
thats what it was, windows makes me so sad.
Woot4Moo
+2  A: 

If you pulled this trick on me as a user of your application, I would be rather annoyed. Why not instead of forcing the user to provide data in a certain format, you reformat the data after the user has entered it?

Take a look at the quotemeta function (perldoc -f quotemeta), which will automatically escape all backslashes (and other potentially-special characters) for you.

Ether
Ill take a look into this, but most likely I won't have a very far least to work with.
Woot4Moo
+1: It should be the program's job to not create odd head scratching things for the user.
drewk
oh i agree whole heartedly drewk, but sometimes you have to rely on the vendor that supplies the tools you use.
Woot4Moo