使用正则表达式搜索NSString

时间:2010-12-04 13:55:03

标签: objective-c cocoa nsstring

我如何使用正则表达式搜索/枚举NSString

正则表达式,例如:/(NS|UI)+(\w+)/g

2 个答案:

答案 0 :(得分:57)

您需要使用NSRegularExpression类。

文档中受到启发的示例:

NSString *yourString = @"";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression         
    regularExpressionWithPattern:@"(NS|UI)+(\\w+)"
    options:NSRegularExpressionCaseInsensitive
    error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
    // your code to handle matches here
}];

答案 1 :(得分:35)

如果您只想匹配字符串中的某些模式,可以使用NSString测试正则表达式的简单方法:

NSString *string = @"Telecommunication";

if ([string rangeOfString:@"comm" options:NSRegularExpressionSearch].location != NSNotFound)

    NSLog(@"Got it");

else

    NSLog(@"No luck");

注意,通常你会想......

if ([string rangeOfString:@"cOMm"
  options:NSRegularExpressionSearch|NSCaseInsensitiveSearch].location
  != NSNotFound)
     NSLog(@"yes match");

在Swift中你可以编写这样的代码......

Swift 2

    let string = "Telecommunication"

    if string.rangeOfString("cOMm", options: (NSStringCompareOptions.RegularExpressionSearch | NSStringCompareOptions.CaseInsensitiveSearch)) != nil {
        print("Got it")
    } else {
        print("No luck")
    }

Swift 4

    let string = "Telecommunication"

    if string.range(of: "cOMm", options: [.regularExpression, caseInsensitive]) != nil {
        print("Got it")
    } else {
        print("No luck")
    }

请注意Swift 2的rangeOfString(_:,options:)和Swift 4的range(of:options:)返回Range<String.Index>?,如果搜索失败则返回nil