1

我需要解析一个类似的字符串[abc]000,而我想要得到的是一个包含abcand的数组000。有没有简单的方法来做到这一点?

我正在使用这样的代码:

NSString *sampleString = @"[abc]000";
NSArray *sampleParts = [sampleString componentsSeparatedByString:@"]"];
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:@"["] lastObject];
NSString *lastPart = [sampleParts lastObject];

但它效率低下,并没有检查字符串是否为[**]**之类的格式。

4

3 回答 3

1

与往常一样,有很多方法可以做到这一点。

选项 1
如果这些是固定长度的字符串(每个部分总是三个字符),那么您可以直接获取子字符串:

NSString *sampleString = @"[abc]000";
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)];
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)];
NSArray *parts = @[ left, right ];
NSLog(@"%@", parts);

选项 1(缩短)

NSArray *parts = @[ [sampleString substringWithRange:NSMakeRange(1, 3)],
                    [sampleString substringWithRange:NSMakeRange(5, 3)] ];
NSLog(@"%@", parts);

选项 2
如果它们不总是三个字符,那么您可以使用NSScanner

NSString *sampleString = @"[abc]000";

NSScanner *scanner = [NSScanner scannerWithString:sampleString];

// Skip the first character if we know that it will always start with the '['.
// If we can not make this assumption, then we would scan for the bracket instead.
scanner.scanLocation = 1;

NSString *left, *right;

// Save the characters until the right bracket into a string which we store in left.
[scanner scanUpToString:@"]" intoString:&left];

// Skip the right bracket
scanner.scanLocation++;

// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist...
[scanner scanUpToString:@"\0" intoString:&right];

NSArray *parts = @[ left, right ];
NSLog(@"%@", parts);

结果(所有选项)

2013-05-10 00:25:02.031 Testing App[41906:11f03] (
    abc,
    000
)

注意
所有这些都假设格式正确的字符串,所以你应该包括你自己的错误检查。

于 2013-05-10T04:38:39.067 回答
1

对于这个简单的模式,可以像这样解析自己:

NSString *s = @"[abc]000";
NSString *firstPart = nil;
NSString *lastPart = nil;
if ([s characterAtIndex: 0] == '[') {
    NSUInteger i = [s rangeOfString:@"]"].location;
    if (i != NSNotFound) {
        firstPart = [s substringWithRange:NSMakeRange(1, i - 1)];
        lastPart = [s substringFromIndex:i + 1];
    }
}

或者你可以学习使用 NSScanner 类。

于 2013-05-10T03:01:36.870 回答
0

试试这样

NSString *sampleString = @"[abc]000";
NSString *pNRegex = @"\\[[a-z]{3}\\][0-9]{3}";
NSPredicate *PNTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pNRegex];
BOOL check=[PNTest evaluateWithObject:sampleString ];
NSLog(@"success:%i",check);

如果success为 1,那么您可以执行将字符串分隔为数组的操作。

于 2013-05-10T04:07:13.460 回答