正则表达式:从//test.test.com/test/1234/获取1234

时间:2015-02-18 10:59:53

标签: ios objective-c regex

我有NSString - @" // test.test.com/test/1234 /"

如何查看包含//test.test.com/test/的字符串并获取1234?

我试过了 -

 NSString *newstr = [string stringByReplacingOccurrencesOfString:@"[^0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];

但它只有数字。

也许我需要使用NSRegularExpressions?但是如何?

2 个答案:

答案 0 :(得分:0)

它帮助我 -

NSString *pattern = @"//test.test.com/test/(\\d+)/";
            NSRegularExpression *regex = [NSRegularExpression
                                          regularExpressionWithPattern:pattern
                                          options:NSRegularExpressionCaseInsensitive
                                          error:nil];
            NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:string options:0 range:NSMakeRange(0, string.length)];

            NSRange matchRange = [textCheckingResult rangeAtIndex:1];
            NSString *match = [string substringWithRange:matchRange];
            NSLog(@"Found string '%@'", match);

答案 1 :(得分:0)

如果您只想要该字符串的右侧组件,那么您需要做的只是...

NSString* str = @"//test.test.com/test/1234/";
NSString* newstr = [str lastPathComponent];     //  Returns "1234"
  

如何查看包含//test.test.com/test/的字符串并获取1234?

如果想要提取最后一个参数,如果你的字符串以//test.test.com/test/开头,那么你可以使用它:

NSString* str = @"//test.test.com/test/1234/";
NSString* lastPart = @"";

if ([str rangeOfString:@"//test.test.com/test"].location != NSNotFound)
{
    lastPart = [str lastPathComponent];
}