簡體   English   中英

Swift / Regex:如何使用stringByReplacingMatches(withTemplate)格式化字符串?

[英]Swift/Regex: How can I format a string using stringByReplacingMatches(withTemplate)?

我想格式化一個數字字符串,例如123456789 ,因此將第一個數字分隔開,然后將每2個數字分組,以得到以下結果:

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}))(?!$)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM