在Swift中用空格分隔某个字符后的值

时间:2016-07-15 00:04:46

标签: regex swift

嗨,我的值是

  

块引用   1 1:0.0644343 1 1:0.0309334 1 1:0.0261616   块引用

我希望按空格分隔值,但在某些字符之后得到这样的结果..是否有任何可能的解决方案。我知道我们可以在正则表达式中做到

  

块引用   “1 1:0.0644343”   “1 1:0.0309334”   “1 1:0.0261616”   块引用

1 个答案:

答案 0 :(得分:1)

我认为正则表达式是完美的工具:

var str = "Blockquote 1 1:0.0644343 1 1:0.0309334 1 1:0.0261616 Blockquote"

let regex = try! NSRegularExpression(pattern: "(\\d \\d:[\\.0-9]+)", options: [])
let matches = regex.matchesInString(str, options: [], range: NSMakeRange(0, str.characters.count))

for m in matches.reverse() {
    let range = m.rangeAtIndex(1)
    let startIndex = str.startIndex.advancedBy(range.location)
    let endindex = startIndex.advancedBy(range.length)
    let value = str[startIndex..<endindex]

    str.replaceRange(startIndex..<endindex, with: "\"\(str[startIndex..<endindex])\"")
}

print(str)