@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