在 Swift 中的前 N ​​个字符后插入字符

发布于 2025-01-11 17:53:45 字数 557 浏览 0 评论 0原文

我返回了一个字符串 let myData = "0000006215342" 并且我只想分隔字符串扩展方法定义的第一个字符

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

调用我的方法的实际结果就像

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

应用我的方法的实际结果是 < code>"000000 621534 2" 但这是错误的,因为我只想分隔第一个字符,例如 "000000 6215342" 如何编辑正则表达式来分隔前 N 个字符?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清眉祭 2025-01-18 17:53:45

您只需将正则表达式模式锚定到字符串的开头:

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

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

let regex = #"^(.{\#(every)})"#
滥情稳全场 2025-01-18 17:53:45

这非常简单,不需要任何正则表达式,只需使用字符串切片:

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"

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文