Swift replace substring regex

前端 未结 6 1525
执念已碎
执念已碎 2020-11-29 04:53

I am attempting to use regular expression to replace all occurrences of UK car registrations within a string.

The following swift code works perfectly for a when the

6条回答
  •  旧巷少年郎
    2020-11-29 05:55

    Swift 4.2 Updated

    let myString = "my car reg 1 - DD11 AAA  my car reg 2 - AA22 BBB"
    if let regex = try? NSRegularExpression(pattern: "([A-HK-PRSVWY][A-HJ-PR-Y])\\s?([0][2-9]|[1-9][0-9])\\s?[A-HJ-PR-Z]{3}", options: .caseInsensitive) {
        let modString = regex.stringByReplacingMatches(in: myString, options: [], range: NSRange(location: 0, length:  myString.count), withTemplate: "XX")
        print(modString)
    }
    

提交回复
热议问题