Regex to determine if path is root directory

3.6k views Asked by At

I am in iOS but pretty much any language will translate.

I am trying to write a regular expression to match a root directory:

ie:

First/ should match
First/file.txt should not match
First/next should not match
First/next/file.txt should not match

So I think the logic should be start at beginning of line match any character except "/" then match "/" only once and that one time should be at the end of the string.

I have:

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\/]*\\/$" options:NSRegularExpressionCaseInsensitive error:&error];

    NSUInteger matches = [regex numberOfMatchesInString:info.name options:NSRegularExpressionCaseInsensitive range:NSMakeRange(0, [info.name length])];
    if (matches > 0) {
      NSLog(@"match");
    } else {
      NSLog(@"not a match");
    }

But its not matching like it should.

Thinking

[^\\/]* 

will match all characters that are not "/"

Then

\\/$

will match a "/" that is at the end of the string.

Where am I going wrong?

1

There are 1 answers

2
rmaddy On BEST ANSWER

The regular expression would be:

^[^/]*/$

This ensures the string ends with a slash and it can contain 0 or more non-slash characters before it.

Another solution (without regular expression) would be this:

NSString *name = ... // some path
if (name.length && [name rangeOfString:@"/"].location == name.length - 1) {
    // root directory
}