How to get matches in iOS using regular expression?

前端 未结 2 1257
不思量自难忘°
不思量自难忘° 2020-12-04 16:06

I got a string like \'stackoverflow.html\' and in the regular expression \'stack(.).html\' I would like to have the value in (.).

I could only find NSPredic

2条回答
  •  孤城傲影
    2020-12-04 16:34

    in iOS 4.0+, you can use NSRegularExpression:

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"stack(.*).html" options:0 error:NULL];
    NSString *str = @"stackoverflow.html";
    NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
    // [match rangeAtIndex:1] gives the range of the group in parentheses
    // [str substringWithRange:[match rangeAtIndex:1]] gives the first captured group in this example
    

提交回复
热议问题