Swift replace substring regex

前端 未结 6 1511
执念已碎
执念已碎 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)

    0 讨论(0)
  • 2020-11-29 05:47

    You need to remove the ^ and $ anchors.

    The ^ means start of string and $ means end of string (or line, depending on the options). That's why your first example works: in the first test string, the start of the string is really followed by your pattern and ends with it.

    In the second test string, the pattern is found in the middle of the string, thus the ^... can't apply. If you would just remove the ^, the $ would apply on the second occurrence of the registration number and the output would be my car reg 1 - DD11 AAA my car reg 2 - XX.

    let myString = "my car reg 1 - DD11 AAA  my car reg 2 - AA22 BBB"
    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: NSRegularExpression.Options.caseInsensitive)
    let range = NSMakeRange(0, myString.count)
    let modString = regex.stringByReplacingMatches(in: myString, options: [], range: range, withTemplate: "XX")
    print(modString)
    // Output: "my car reg 1 - XX  my car reg 2 - XX"
    
    0 讨论(0)
  • 2020-11-29 05:53

    With pattern: "^ ... $" you have specified that the pattern is anchored to the start and end of the string, in other words, the entire string must match the pattern. Just remove ^ and $ from the pattern and you'll get the expected result.

    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2020-11-29 05:56

    Update for Swift 2.1:

    var 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.stringByReplacingMatchesInString(myString, options: .WithTransparentBounds, range: NSMakeRange(0, myString.characters.count), withTemplate: "XX")
        print(modString)
    }
    
    0 讨论(0)
  • 2020-11-29 05:56

    Warning

    Do not use NSRange(location: 0, length: myString.count) as all examples above quoted.

    Use NSRange(myString.startIndex..., in: myString) instead!

    .count will count newline characters like \r\n as one character - this may result in a shortened, thus invalid, NSRange that does not match the whole string.

    (.length should work)

    0 讨论(0)
提交回复
热议问题