以编程方式格式化swift中的字符串

时间:2015-04-12 17:49:53

标签: macos swift

我有字符串

var arrayWithStrings = ["813 - Crying Flute.mp3", "Ark Patrol - Never.mp3"]

我想要

var stringTitle1 = "813"
var stringNameOfTrack1 = "CryingFlute"
var stringFormat1 = "mp3"
var stringTitle2 = "Ark Patrol"
var stringNameOfTrack2 = "Never"
var stringFormat2 = "mp3"

如何以编程方式完成?

1 个答案:

答案 0 :(得分:4)

您可以使用正则表达式:

let string = "813 - Crying Flute.mp3"

let regex = try! NSRegularExpression(pattern: "^(.*) - (.*)\\.(.*)$")

if let match = regex.firstMatch(in: string, range: string.nsRange) {
    let title  = string[match.range(at: 1)]
    let name   = string[match.range(at: 2)]
    let format = string[match.range(at: 3)]
}

在Swift 4中的位置:

extension String {

    /// An `NSRange` that represents the full range of the string.

    var nsRange: NSRange {
        return NSRange(startIndex ..< endIndex, in: self)
    }

    /// Substring from `NSRange`
    ///
    /// - Parameter nsRange: `NSRange` within the string.
    /// - Returns: `Substring` with the given `NSRange`, or `nil` if the range can't be converted.

    subscript(nsRange: NSRange) -> Substring? {
        return Range(nsRange, in: self)
            .flatMap { self[$0] }
    }
}

正则表达式的()是“捕获括号”以标识可由range(at:)标识的子字符串。