我需要解析像[abc]000
这样的字符串,而我想要的是一个包含abc
和000
的数组。有没有简单的方法呢?
我正在使用这样的代码:
NSString *sampleString = @"[abc]000";
NSArray *sampleParts = [sampleString componentsSeparatedByString:@"]"];
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:@"["] lastObject];
NSString *lastPart = [sampleParts lastObject];
但它效率低,并没有检查字符串是否采用[**] **格式。
答案 0 :(得分: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类。
答案 1 :(得分: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
)
注意强>
所有这些都假设格式良好的字符串,因此您应该包含自己的错误检查。
答案 2 :(得分: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,则可以执行将字符串分隔为数组的操作。