Search code examples
iosarraysswiftstringuikit

How to extract a negative number from a String?


I have a string with a math equation which can contain a negative number "-6-9".

I need to extract all numbers from this string and put them into a numbersArray:

let numbersArray = string.components(separatedBy: CharacterSet(charactersIn: "+-x/"))

Output I need: ["-6", "9"]

Output I receive: ["", "6", ""]

I think it's because I have a string with doubled characters. In my case I have two minuses in the string (-) and with this minus I am trying to separate the string.

How can I separate the numbers in the string properly to receive a desired output?


Solution

  • You can do that with regex, something like this will do:

     do {
            let string = "-6-9"
            let regex = try NSRegularExpression(pattern: "[\\+\\-][0-9]+")
            let results = regex.matches(in: string,
                                        range: NSRange(string.startIndex..., in: string))
            let res = results.map {
                String(string[Range($0.range, in: string)!])
            }
            print(res.compactMap { Int($0) })
        }
        catch {
    
        }
    

    Output:

    [-6, -9]