如何拆分此字符串并在ios正则表达式中单独获取数字

时间:2014-12-09 08:56:50

标签: ios regex nsstring nsregularexpression

我有NSString这样的“media_w940996738_476.mp3”我想分别得到这个“476”号码。如何使用正则表达式从此NSString中获取它。

5 个答案:

答案 0 :(得分:3)

如果您始终想要在文件扩展名之前找到以下划线分隔的最后一个值,请使用以下代码:

NSString *mediaName = [[fileName componentsSeparatedByString:@"."] firstObject];
int requiredNumber = [[[mediaName componentsSeparatedByString:@"_"] lastObject] intValue];

答案 1 :(得分:1)

Here is your regex. for this

NSString *yourString = @"media_w940996738_476.mp3";
NSError *error = NULL;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"([0-9]{3})([.]{1})" options:NSRegularExpressionCaseInsensitive error:&error];


[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

    // detect
    NSString *insideString = [yourString substringWithRange:[match rangeAtIndex:1]];

    //print
    NSLog(@"%@",insideString);

}];

答案 2 :(得分:1)

你可以使用正则表达式:

NSString *string = @"media_w940996738_476.mp3";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"_([:digit:]+)\\." options:NSRegularExpressionCaseInsensitive error:nil];

    [regex enumerateMatchesInString:string options:0 range:NSMakeRange(0, [string length]) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        // detect
        NSString *insideString = [string substringWithRange:[result rangeAtIndex:1]];
        //print
        NSLog(@"%@",insideString);
    }];

答案 3 :(得分:0)

如果您 并非绝对需要正则表达式 ,则只需使用以下内容:

NSInteger value = [[[fileName componentsSeparatedByString:@"_"] lastObject] integerValue];

调用componentsSeparatedByString:@"_"将返回一个数组,lastObject将为476.mp3

获取integerValue应该返回476

答案 4 :(得分:0)

使用正则表达式,您可以搜索以<.mp3 (\d)+结尾的一个或多个数字 (\.mp3)$

NSString *filename = @"media_w940996738_476.mp3";

NSError *error = NULL;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+)(\\.mp3)$" options:NSRegularExpressionCaseInsensitive error:&error];

NSRange textRange = NSMakeRange(0, filename.length);
NSTextCheckingResult *match = [[regex matchesInString:filename options:0 range:textRange] firstObject];
NSString *matchedString = [filename substringWithRange:[match rangeAtIndex:1]];

NSLog(@"%@", matchedString);

如果要匹配具有不同扩展名的文件名,可以通过列出它们来更改正则表达式模式:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+)(\\.(mp3|m4a|m4b|aa))$" options:NSRegularExpressionCaseInsensitive error:&error];

匹配任何带有2或3个字符扩展名的文件名:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+)(\\.\\b\\w{2,3})$" options:NSRegularExpressionCaseInsensitive error:&error];