ios - 在 : and before? 之后拆分字符串

标签 ios objective-c nsstring

我有一个像这样的长字符串:

je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?

我想在 : 之后和之前拆分字符串? .所以我想把它放入数组中:

{e,es,e,ons,ez,en}

我知道我可以做到:

 NSArray *subStrings = [stringToChange componentsSeparatedByString:@":"];

但这还不够。 请问我该怎么做?任何帮助将不胜感激!

最佳答案

另一种选择是使用 NSRegularExpression类。

使用这种模式:

\\:([^\?]+)\?

示例代码:

NSString *sample  = @"je!tress:e?tu!tress:es?il!tress:e?nous!tress:ons?vous!tress:ez?ils!tress:ent?";
NSString *pattern = @"\\:([^\?]+)\?";

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                       options:NSRegularExpressionCaseInsensitive
                                                                         error:&error];


NSArray *matches = [regex matchesInString:sample
                                  options:0
                                    range:NSMakeRange(0, [sample length])];
if(!error && [matches count] > 0) {
    for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match range];
        NSLog(@"%@" ,[sample substringWithRange:matchRange]);
    }
}

输出:

2015-07-03 12:16:39.037 TestRegex[3479:48301] :e
2015-07-03 12:16:39.039 TestRegex[3479:48301] :es
2015-07-03 12:16:39.039 TestRegex[3479:48301] :e
2015-07-03 12:16:39.040 TestRegex[3479:48301] :ons
2015-07-03 12:16:39.040 TestRegex[3479:48301] :ez
2015-07-03 12:16:39.040 TestRegex[3479:48301] :ent

关于ios - 在 : and before? 之后拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31200088/

相关文章:

ios - 使用 Kiwi 捕获静态方法调用的参数

objective-c - iOS旋转使用tabBar Controller 锁定为纵向

iphone - MKPolylineView lineWidth 每次在 MKMapview 上放大或缩小时都需要相同

iphone - 通过空格将 1 个 NSString 分成两个 NSString

iPhone/Objective-C - 将字符串传递给方法时出现奇怪的错误

iphone - NSString 中子字符串之后的子字符串

iOS - 数据在 Core Data 中保存一次

android - 将 flex 移动项目转换为 flex web 项目

ios - Dropbox API iOS 不上传文件

objective-c - 如何通过触摸和滑动来移动和滑开 UIView?