繁体   English   中英

使用正则表达式搜索NSString

[英]Search through NSString using Regular Expression

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

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

您需要使用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
}];

如果您只想匹配字符串中的某些模式,可以使用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中你可以编写这样的代码......

斯威夫特2

    let string = "Telecommunication"

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

斯威夫特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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM