0

Example String -

exampleString ( 123 )

I want two parts from the above string -

1-) exampleString by splitting

2-) 123 by splitting and then removing brackets and two spaces, one at each end

More specifically, I want to know how can I extract a string between two brackets ( )

How to achieve that in swift 4.2?

Thanks

Master AgentX
  • 397
  • 2
  • 18

2 Answers2

1

There is a solution below, it will extract any string between brackets into an array without brackets, it also gives you string without element as word as an array element:

var myString = "exampleString ( 123 ) "

//creates result array from String by separating elements by space
var result = myString.split(separator: " ")

//filters array to remove '(' and ')'
result = result.filter { $0 != "(" && $0 != ")" }

print(result)

Then if you want to build a String back from result array with string elements, do the following:

var resultString = result.joined(separator: " ")

print(resultString)

Might not be ideal, but it might be useful for you.

emrepun
  • 2,496
  • 2
  • 15
  • 33
  • 1
    Worked for me, I answered my own question but serving just one purpose. But your's served both purposes. Thanks! – Master AgentX Jan 26 '19 at 09:21
  • This is not what OP asked – Leo Dabus Jan 26 '19 at 13:06
  • @MasterAgentX if you need to get all words from a string you can use string method enumerateSubstrings(in Range) https://stackoverflow.com/questions/37535441/extract-last-word-in-string-with-swift/37536996#37536996 – Leo Dabus Jan 26 '19 at 13:12
1

I found this beautiful String Extension for slicing a string. It is answered here -

Slice String Extension

extension String {
    func slice(from: String, to: String) -> String? {
        return (range(of: from)?.upperBound).flatMap { substringFrom in
        (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
            String(self[substringFrom..<substringTo])
            }
        }
    }
}

Here I can simply get a substring like

let str = "exampleString ( 123 )"
print(str.slice(from: "( ", to: " )"))
Master AgentX
  • 397
  • 2
  • 18