How to get matches in iOS using regular expression?

前端 未结 2 1258
不思量自难忘°
不思量自难忘° 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:32

    You want the RegexKitLite library in order to perform regular expression matches:

    http://regexkit.sourceforge.net/RegexKitLite/

    After that it's almost exactly like you do it in PHP.

    I'll add some code to help you with it:

    NSString *string     = @"stackoverflow.html";
    NSString *expression = @"stack(.*)\\.html";
    NSString *matchedString = [string stringByMatching:expression capture:1];
    

    matchedString is @"overflow", which should be exactly what you need.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题