Reputation: 24316
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.
Upvotes: 1
Views: 1849
Reputation: 53966
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.
Upvotes: 2
Reputation: 336108
^(\\\\|[^\\])*$
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.
Upvotes: 4