Jason Kim
Jason Kim

Reputation: 19031

Ruby regex: validate unix file path

I want to validate unix file path using regex.

I have \A[0-9a-zA-Z\_\-\/]+\z

But this still allows double slashes like this//is//allowed

How do I make sure double slashes are not allowed?

edit 1

I want to allow _, -, alphanumeric values as long as they form valid unix directory path. Just want to make sure that // is forbidden. THanks

Upvotes: 1

Views: 3894

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213223

You should move the slash outside the character class, and make it optional. And then add quantifier on the character class and the slash combined, to repeat their combination for 1 or more times:

\A(?:[0-9a-zA-Z_-]+\/?)+\z

See on http://rubular.com/r/77kvWAoI4e

(?:
  [0-9a-zA-Z_-]+   # Original character class without `/`. 
  \/?                # An optional slash (Because the string need not end with `/`
)+                   # 1 or more repetition of their combination

And you don't need to escape _ in regex. And also - when used at the end of character class.

And finally, your character class can be reduced to - [\w-]. So, your regex can be reduced to:

\A(?:[\w-]+\/?)+\z

Upvotes: 4

New Alexandria
New Alexandria

Reputation: 7324

Specify the target character along with the number of times it is repeated

/\/{2}/

Upvotes: 0

Related Questions