简体   繁体   English

替换出现的字符串模式

[英]Replace occurrences of string pattern

So this is a string I get back from the server: 所以这是我从服务器返回的字符串:

var arrayString = "IT34:1, IT35:2, IT36:1, IT35:3"

I want to get rid of any occurrences of ":1", ":2" and am using: 我想摆脱任何出现的“:1”,“:2”,并且正在使用:

let cleanStr = arrayString.stringByReplacingOccurrencesOfString(":1", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

let cleanStr1 = cleanStr.stringByReplacingOccurrencesOfString(":2", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)

And so on... 等等...

Which doesn't seem very efficient. 这似乎不是很有效。 Is it possible to accomplish this with just one .stringByReplacingOccurrencesOfString method? 是否可以仅使用一个.stringByReplacingOccurrencesOfString方法来完成此.stringByReplacingOccurrencesOfString Like occurrences of ":(a number)"? 喜欢出现“:(a)”吗?

This can be done using regular expressions: 这可以使用正则表达式来完成:

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)

And in Objective-C: 在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);

I do not know the exact pattern of those ":1" thingies, but here's a solution you might fiddle with: 我不知道这些“:1”事物的确切模式,但是您可以尝试以下解决方案:

let cleanStr = ", ".join(arrayString.componentsSeparatedByString(", ").map { ($0 as NSString).substringToIndex(4) })

This solution will work as long as the ':1" things have one digit. 只要':1“内容为一位,此解决方案就可以使用。

Here's a general solution: 这是一个常规解决方案:

let cleanStr = ", ".join(arrayString.componentsSeparatedByString(", ").map {
    ($0 as NSString).componentsSeparatedByString(":")[0] as String
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM