NSString分类
@implementation NSString (GC)
- (NSString *)suffix_Num {
// 匹配字符串末尾的数字
NSString *pattern = @"\\d+$";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
if (error) {
CHLog(@"正则表达式错误:%@", error);
return @"";
}
else {
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:self options:0 range:NSMakeRange(0, self.length)];
if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
NSString *numberString = [self substringWithRange:rangeOfFirstMatch];
CHLog(@"提取到的数字:%@", numberString);
return numberString;
}
else {
CHLog(@"未找到匹配的数字");
return @"";
}
}
}
@end
使用
NSString *num_string = [@"ABC123" suffix_Num];
CHLog(@"提取到的数字:%@", num_string);
// 结果为 123
作者: CH520
标签:CHLog,数字,后缀,numberString,NSString,rangeOfFirstMatch,error,字符串 From: https://blog.51cto.com/u_15318120/8016289