您的位置:首页 > 移动开发 > IOS开发

在iOS开发中使用正则表达式分解字符串

2016-08-11 18:19 483 查看
例:将下列字符串中方括号[]中的内容提取出来并形成一个Array:

NSString* entry = @"[field1] [field2] [field3] [field4] [field5]";


解法一:使用componentsSeparatedByString:方法分解:

NSArray *rawFields = [entry componentsSeparatedByString:@"] ["];
NSMutableArray *fields = [NSMutableArray arrayWithArray:rawFields];

//Remove '[' from the first field
NSString* firstRawField = [rawFields[0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if([firstRawField hasPrefix:@"["] && [firstRawField length] > 1){
[fields replaceObjectAtIndex:0 withObject:[firstRawField substringFromIndex:1]];
}

//Remove ']' from the last field
NSString* lastRawField = [rawFields[rawFields.count - 1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if([lastRawField hasSuffix:@"]"] && [lastRawField length] > 1){
[fields replaceObjectAtIndex:(rawFields.count - 1) withObject:[lastRawField substringToIndex:[lastRawField length] - 1]];
}


解法二:使用正则表达式分解:

__block NSMutableArray *fields = [[NSMutableArray alloc] init];
NSError *error = NULL;
NSRegularExpression *fieldRegularExpression = [NSRegularExpression
regularExpressionWithPattern:@"\\[[^\\]]*\\]"
options:NSRegularExpressionCaseInsensitive
error:&error];
[fieldRegularExpression enumerateMatchesInString:entry options:0 range:NSMakeRange(0, [entry length])
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
if(match.range.length > 2) {
NSRange range = NSMakeRange(match.range.location + 1, match.range.length - 2);  //Remove '[' and ']'
[fields insertObject:[entry substringWithRange:range] atIndex:fields.count];
} else {
[fields insertObject:EMPTY_STRING atIndex:fields.count];
}

}];


这里,正则表达式

@"\\[[^\\]]*\\]"


的意义为左右方括号中包含任意长度的字符串,且字符串不含右方括号’]’。

复习:正则表达式中,’\’代表转义字符,’[^list]’代表不含的字符集,’*’代表重复0到无穷多个前一个字符。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息