Home > OS >  Insert character after first N characters in Swift
Insert character after first N characters in Swift

Time:03-05

I have an String returned let myData = "0000006215342" and I want to separate only the firs characters defined by a String extension method

    func separating(every: Int, separator: String) -> String {
       let regex = #"(.{\#(every)})(?=.)"#
       return self.replacingOccurrences(of: regex, with: "$1\(separator)", options: [.regularExpression])
    }

The actual result calling my method are like

mylabel.text = myData.separating(every: 6, separator: " ")

The actual result of applying my method are "000000 621534 2" but this is wrong because I want to separate only the first characters like "000000 6215342" how I can edit my regex to separate my first N characters ?

CodePudding user response:

You just need to anchor your regex pattern to the start of the string:

let regex = #"^(.{\#(every)})"#

CodePudding user response:

This is really simple to do without any regular expressions being required, just using a String slice:

extension String {
    func separating(every groupSize: Int, separator: String) -> String {
        guard let separatorIndex = index(startIndex, offsetBy: groupSize, limitedBy: endIndex) else {
            return self // The string is too short so no separators are necessary 
        }
        return String(self[..<separatorIndex]   Substring(separator)   self[separatorIndex...])
    }
}

let myData = "0000006215342"
let result = myData.separating(every: 6, separator: " ")
print(result) // => "000000 6215342"
  • Related