使用正则表达式搜索NSString

Jos*_*hua 40 cocoa objective-c nsstring

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

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

Pab*_*ruz 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
}];
Run Code Online (Sandbox Code Playgroud)

  • Joshua - `\ w`确实是正确的元字符,但反斜杠字符在普通字符串中用作转义字符.编译器的字符串解析器会在传递给RegEx对象之前将`\ w`更改为简单的`w`.运行NSLog以便自己查看.因此正确的表示法是`\\ w`,因为编译器会将'\\'转换为'\'.该惯例以多种语言呈现. (13认同)
  • 这是我使用的代码,包括字符串 https://gist.github.com/728216。但是它不起作用并且不调用`NSLog`。 (2认同)

ved*_*ano 35

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

NSString *string = @"Telecommunication";

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

    NSLog(@"Got it");

else

    NSLog(@"No luck");
Run Code Online (Sandbox Code Playgroud)

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

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

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

斯威夫特2

    let string = "Telecommunication"

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

斯威夫特4

    let string = "Telecommunication"

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

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