【问题标题】:Searching for substrings (NSString)搜索子字符串(NSString)
【发布时间】:2011-09-25 10:02:53
【问题描述】:

搜索由## $$ 括起来的子字符串的最佳方法是什么?例如,我有一些这样的文字:

Lorem ##ipsum$$ dolor sit amet,##consectetur$$ adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat。

我想得到 ipsumconsectetur 这两个词。我知道我可以使用 NSString rangeofsubstring 方法,但是有更好的方法吗?基本上,找到一个由其他 2 个字符串包围的字符串? 谢谢

【问题讨论】:

    标签: objective-c ios cocoa-touch nsstring substr


    【解决方案1】:

    您可以使用 NSRegularExpression(警告:仅限 iOS4+)使用 RegEx 模式匹配您的子字符串(通常像 @"##.*$$")。

    然后很容易遍历结果匹配(我首选的方法是使用枚举块,因为我们是 un iOS4 :-)):

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"##(.*)$$" options:NSRegularExpressionCaseInsensitive error:nil];
    [regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:
        ^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) {
            NSRange range = [match rangeAtIndex:1]; // range of string in first parens
            NSString* oneWord = [yourString substringWithRange:range];
        }
    ];
    

    注意:如果你需要支持 pre-iOS4 版本,你可以查看NSPredicate 但它的灵活性要差得多(...我猜对于 pre-iOS4,使用 rangeOfSubstring 可能是最好的选择无论如何,因为 NSPredicate 只会告诉您字符串是否匹配,但不允许您获取子字符串...)

    【讨论】:

      【解决方案2】:

      遍历字符串字符,搜索“##”,然后搜索最近的“$$”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-06
        • 2017-02-09
        • 2011-02-10
        • 2011-11-30
        相关资源
        最近更新 更多