简体   繁体   中英

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:

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? Like occurrences of ":(a number)"?

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:

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:

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

This solution will work as long as the ':1" things have one digit.

Here's a general solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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