Swift replace substring regex

前端 未结 6 1523
执念已碎
执念已碎 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:36

    Let's use a class extension to wrap this up in Swift 3 syntax:

    extension String {
        mutating func removingRegexMatches(pattern: String, replaceWith: String = "") {
            do {
                let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
                let range = NSRange(0, count)
                self = regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: replaceWith)
            } catch { return }
        }
    }
    
    var phoneNumber = "+1 07777777777"
    phoneNumber.removingRegexMatches(pattern: "\\+\\d{1,4} (0)?")
    

    Results in 7777777777 (thus removing country code from phone number)

提交回复
热议问题