Kevin Mann
Kevin Mann

Reputation: 741

Finding text between parentheses in Swift

How do you get an array of string values for the text between parentheses in Swift?

For example from: MyFileName(2015)(Type)(createdBy).zip

I would like: [2015,Type,createdBy]

Upvotes: 2

Views: 5314

Answers (4)

KarimIhab
KarimIhab

Reputation: 173

Here is a complete example in Swift 4.2

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

do {

    let regex = try NSRegularExpression(pattern: regex, options: [])
    let nsString = text as NSString

    let results = regex.matches(in: text,
                                        options: [], range: NSMakeRange(0, nsString.length))
    return results.map { nsString.substring(with: $0.range)}

} catch let error as NSError {

    print("invalid regex: \(error.localizedDescription)")

    return []
}}

and usage :

let regex = "\\((.*?)\\)"
mmatchesForRegexInText(regex: regex, text: " exmaple (android) of (qwe123) text (heart) between parentheses")

Upvotes: 4

Dimas Mendes
Dimas Mendes

Reputation: 2802

Just updating the chosen answer to Swift 3:

func matchesForRegexInText(regex: String!, text: String!) -> [String] {

do {

    let regex = try NSRegularExpression(pattern: regex, options: [])
    let nsString = text as NSString

    let results = regex.matches(in: text,
                                        options: [], range: NSMakeRange(0, nsString.length))
    return results.map { nsString.substring(with: $0.range)}

} catch let error as NSError {

    print("invalid regex: \(error.localizedDescription)")

    return []
}}

The usage remains the same.

Upvotes: 4

karthik
karthik

Reputation: 621

Here is my RegEx which is actually trying to get the words between parentheses. E.g. (smile)

NSRegularExpression(pattern: "\\\\(\\\w+\\\\)",options:NSRegularExpressionOptions.CaseInsensitive)

it works for me!

Upvotes: 0

siegy22
siegy22

Reputation: 4413

You can use a regex for this

Thomas had a good example: \((.*?)\)

How to use a regex with Swift you can look up at: http://www.raywenderlich.com/86205/nsregularexpression-swift-tutorial

Upvotes: 0

Related Questions