0
点赞
收藏
分享

微信扫一扫

【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

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


 

举报

相关推荐

0 条评论