簡體   English   中英

如何在iOS正則表達式中拆分此字符串並分別獲取數字

[英]How to split this string and get the number separately in ios regular expression

我有一個像這樣的NSString “ media_w940996738_476.mp3”,我想分別獲得這個“ 476”號。 如何使用正則表達式從此NSString中獲取它。

如果您始終想找出文件擴展名前用下划線分隔的最后一個值,請使用以下代碼:

NSString *mediaName = [[fileName componentsSeparatedByString:@"."] firstObject];
int requiredNumber = [[[mediaName componentsSeparatedByString:@"_"] lastObject] intValue];
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);

}];

您可以使用正則表達式:

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);
    }];

如果您絕對不需要正則表達式可以使用以下命令:

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

調用componentsSeparatedByString:@"_"將返回一個數組,並且lastObject將為476.mp3

獲得integerValue應該返回476

使用正則表達式,您可以搜索以.mp3 (\\.mp3)$ 結尾的 一個或多個數字 (\\d)+

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];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM