Apple开发_字符串后缀如果包含有数字,提取出字符串后缀全部的数字

  • 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
posted @ 2023-09-13 10:52  CH520  阅读(12)  评论(0编辑  收藏  举报