问题描述:
校验如下字符串格式是否符合要求(括号成对出现,且数量无限制)
(((a+b)*(c+d))+c)*(((a+b)*(c+d))+(d+e+c)+(w*i))
遇到这个问题,我第一想到的就是正则是不是有支持递归校验的功能,然后百度了好久,发现不是所有语言都支持递归校验的。最终没能找到合适的方案,只能曲线救国了。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *str1 = @"(((a+b)*(c+d))+c)*(((a+b)*(c+d))+(d+e+c)+(w*i))";
//NSString *str2 = @"(((a+b)*(c+d))+c)*(((a+b)*(c+d))+(d+e+c)+(w*i)))";
BOOL b = [self isValidString:str1];
NSLog(@"%d",b);
}
校验方法
- (BOOL)isValidString:(NSString *)str {
NSString *pattern = @"\\([^\\(^\\)]*?\\)";
NSString *pattern2 = @"\\(|\\)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
NSArray * rlts ;
while ((rlts = [regex matchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, str.length)]).count) {
//找出最小单位的成对括号,并用下划线替换
str = [regex stringByReplacingMatchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, str.length) withTemplate:@"_"];
}
/ /最后检查一次,如果还存在左括号或者右括号,说明出现了不成对的情况
regex = [NSRegularExpression regularExpressionWithPattern:pattern2 options:NSRegularExpressionCaseInsensitive error:NULL];
rlts = [regex matchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, str.length)];
return rlts.count == 0;
}
当输入str1时,结果为1,输入str2,结果为0
网友评论