2

I have strings

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

I want to get

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

How to do it programmatically?

2
  • 1
    You can use Regular Expression to match every element in the array as you want. Commented Apr 12, 2015 at 17:57
  • @Rob No, i need to get it from array elements. Commented Apr 12, 2015 at 17:57

1 Answer 1

4

You can use regular expressions:

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)]
}

Where, in 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] }
    }
}

The regular expression's ( and ) are "capturing parentheses" to identify the substrings, that can be identified by range(at:).

Sign up to request clarification or add additional context in comments.

2 Comments

@Rob I though you have an error in the pattern , it should be "^(.*) - (.*)\\.(.*)$" because the beginning isn't always a number, it could be letters regarding the array in the question
Good catch. Thanks. I was just focusing on the first example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.