【ios】字符串中正则表达式使用

Hwaphon 2017-02-24

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

参考:

1.去除空格:http://blog.csdn.net/yangtb2010/article/details/7925546

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

3.字符串正则方法:http://www.jianshu.com/p/588fcd6ec3aa

4.在线正则测试:http://tool.oschina.net/regex/

5.字符串操作大全:http://blog.csdn.net/newjerryj/article/details/6262893

相关推荐