草庐IT

ios - swift/正则表达式 : How can I format a string using stringByReplacingMatches(withTemplate)?

coder 2023-09-13 原文

我想格式化一个数字字符串,例如123456789,所以第一个数字会被分开,然后每两个数字被分组,得到这个结果:

1 23 45 67 89

我试过这个:

let givenText = "123456789"
let text = (try? NSRegularExpression(pattern: "([0-9])([0-9])(?!$)",
                                     options: .caseInsensitive))?
.stringByReplacingMatches(in: givenText,
                          options: .reportProgress,
                          range: NSMakeRange(0, givenText.count),
                          withTemplate: "$0 ")

但我得到的是这个结果:

12 34 56 78 9

我不知道如何隔离第一个数字。 感谢您的帮助。

最佳答案

您需要更改正则表达式以匹配字符串开头的一个数字或两个数字。

((^[0-9])|([0-9]{2}))(?!$)

关于ios - swift/正则表达式 : How can I format a string using stringByReplacingMatches(withTemplate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57714332/

有关ios - swift/正则表达式 : How can I format a string using stringByReplacingMatches(withTemplate)?的更多相关文章

随机推荐