在 Swift 中的前 N 个字符后插入字符
我返回了一个字符串 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需将正则表达式模式锚定到字符串的开头:
You just need to anchor your regex pattern to the start of the string:
这非常简单,不需要任何正则表达式,只需使用字符串切片:
This is really simple to do without any regular expressions being required, just using a String slice: