0

I am trying to implement similar functionality of change directory (cd) in command prompt.

The restriction is that, 
1 . directory names must only contain alphabets.
2 . root directory is "/"
3 . parent directory is ".."
4 . path separator is "/"

The input will be the new path name .

Input might be like . 
1. directory name alone. - valid
2. directory/directory/directory - valid
3. directory//directory - invalid
4. .. - valid
5. directory/.. - valid
6. directory/... - invalid

and other combinations like that.

To avoid complexity I tried to split the check

  1. To check input must contain only letters, I used ^[A-Za-z]+$ this.
  2. But don't know how to restrict the / and dot(.) characters subsequent occurences to 1 and 2 respectively

Thanks

  • Please write a better title based on your specific problem http://meta.stackexchange.com/questions/10647/how-do-i-write-a-good-title – Soner Gönül Apr 05 '15 at 09:25
  • I wouldn't go the regex route, you're going to blow your head off. Perhaps see if this will help you? http://stackoverflow.com/questions/422090/in-c-sharp-check-that-filename-is-possibly-valid-not-that-it-exists – Erti-Chris Eelmaa Apr 05 '15 at 10:14
  • @Erti-ChrisEelmaa : 1 . in my scenario, input ( director / folder name ) must containt only alphabets, but windows allows numbers and certain special characters. 2 . Without regex, It would be simple if the input is simple like only one directory name at a time,( ex: cd folder). But what is the command is like ( cd ../folder/../../../../../../../123 ), something like that, to get the error ( number are not allowed ), I may need to iterate nearly 10 time which is waste at last rite. – Jonathon Gohan Apr 05 '15 at 10:35
  • Do a simple check if all the characters in string are either: A-Za-z, ., or /, then run it through FileInfo class as in the link I gave to check if it's valid? – Erti-Chris Eelmaa Apr 05 '15 at 11:56

1 Answers1

0

You can simply use String.IndexOf and check against it's return value.

var is_only_one_slash = input.IndexOf("\\\\") == -1;
var is_only_two_dots = input.IndexOf("..") > -1;
if(is_only_one_slash && is_only_two_dots) {
  // valid
} 
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • Thanks Amit, actually I need like, only 2 dot characters (..) and only one / character. Also, I couldn't find Test method in Regex( I am using System.Text.RegularExpressions ) – Jonathon Gohan Apr 05 '15 at 09:42
  • @JonathonGohan check my edit. It should work now without any regex at all. – Amit Joki Apr 05 '15 at 09:47
  • Amit, I have edited the question. pls check. Yeah I think I might use that indexOf for slash .But it might overlook scenario more than 2 dots, rite. 1. ... - it will be treated as valid – Jonathon Gohan Apr 05 '15 at 10:08