天天看點

【ios】字元串中正規表達式使用

java:

public static String convertToMacAddress(String unformattedMAC) {

        String formattedMAC = "";

        char divisionChar = ':';
        if (!unformattedMAC.isEmpty()) {
            formattedMAC = unformattedMAC.trim();
            formattedMAC = formattedMAC.replaceAll("(.{2})", "$1" + divisionChar).substring(0, 17).toUpperCase();
        }

        return formattedMAC;
    }      

2.ios中

-(NSString*)converToMacAddress:(NSString*)unformattedMAC{
    NSMutableString *formattedMAC = [NSMutableString stringWithString:@""];
    
    char divisionChar = ':';
    if (!(unformattedMAC.length == 0)) {
        //trim
       formattedMAC = [unformattedMAC stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *str = [NSString stringWithFormat:@"$1%c",divisionChar];
        NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:@"(.{2})" options:NSRegularExpressionCaseInsensitive error:nil];
        formattedMAC = [regExp stringByReplacingMatchesInString:formattedMAC options:NSMatchingReportProgress range:NSMakeRange(0, formattedMAC.length) withTemplate:str];
     //substring to last one ':'
    formattedMAC = [formattedMAC substringWithRange:NSMakeRange(0,formattedMAC.length-1)];
}
    return formattedMAC;
}      

結果:

輸入:0095699964c4

輸出:00:95:69:99:64:c4

參考:

2.截取字元:http://www.cocoachina.com/bbs/read.php?tid=89685