所以这是我从服务器回来的字符串:
var arrayString = "IT34:1, IT35:2, IT36:1, IT35:3"
我想摆脱任何":1",":2"并且正在使用:
let cleanStr = arrayString.stringByReplacingOccurrencesOfString(":1", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
let cleanStr1 = cleanStr.stringByReplacingOccurrencesOfString(":2", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
等等......
这看起来效率不高。只用一个.stringByReplacingOccurrencesOfString
方法就可以做到这一点吗?就像" :(一个数字)"?
答案 0 :(得分:5)
这可以使用正则表达式来完成:
let string = "IT34:1, IT35:2, IT36:1, IT35:3"
var cleanStr = string
if let regex = NSRegularExpression(pattern: ":[0-9]", options:.CaseInsensitive, error: nil) {
cleanStr = regex.stringByReplacingMatchesInString(string, options: nil, range: NSMakeRange(0, countElements(string)), withTemplate: "")
}
println(cleanStr)
在Objective-C中:
NSString *string = @"IT34:1, IT35:2, IT36:1, IT35:3";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@":[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
NSString *newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", newString);
答案 1 :(得分:0)
我不知道那些":1"的确切模式。好东西,但这里有一个你可以解决的解决方案:
let cleanStr = ", ".join(arrayString.componentsSeparatedByString(", ").map { ($0 as NSString).substringToIndex(4) })
这个解决方案只要' 1"事情有一位数。
这是一般解决方案:
let cleanStr = ", ".join(arrayString.componentsSeparatedByString(", ").map {
($0 as NSString).componentsSeparatedByString(":")[0] as String
})