1

I'm trying to extract some numbers within a parenthesis in swift.

Eg.

var accname = "(1234) some random texts"

How to get 1234 from var s ? The numbers in the bracket does not have a fixed length. It can be (12) or (12345).

This is what I have tried

var accname = ""
for i in accname.characters.indices[(accname.startIndex)..<accname.endIndex]{

       while accname[i] != ")"{
                accnumb.append(accname[i])
        }
        }
Nee
  • 71
  • 3
  • 10
  • Related: https://stackoverflow.com/questions/36941365/swift-regex-for-extracting-words-between-parenthesis, https://stackoverflow.com/questions/33693021/finding-text-between-parentheses-in-swift. – Martin R Jun 12 '17 at 07:08

3 Answers3

6

Well you can use below extension suggested by @oisdk for that:

var demoText = "(1234)  e e e er er e"

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


let sliced  = demoText.slice(from: "(", to: ")")
Joannes
  • 2,569
  • 3
  • 17
  • 39
ankit
  • 3,537
  • 1
  • 16
  • 32
0

There are a couple of things wrong with your code:

  • replace the while with a if
  • use for ... in ... for the actual characters, not the index
  • drop the first char
  • stop the entire logic as soon as you encounter a )

That results in the following code without changing your basic logic:

let accname = "(1234) some random texts"
var accnumb = ""
for char in accname.characters.dropFirst() {
    if char != ")" {
        accnumb.append(char)
    } else {
        break
    }
}
print(accnumb) // 1234
luk2302
  • 55,258
  • 23
  • 97
  • 137
0

Here is another extension you could use, it creates a string containing all numeric values and uses that for filtering:

extension String {
    var numericString: String? {
        let numericValues = "1234567890"
        let filteredString = self.characters.filter {
            return numericValues.contains(String($0))
        }
        guard filteredString.count > 0 else {
            return nil
        }
        return String(filteredString)
    }
}

let value = "(1234)"
let numericString = value.numericString // "1234"

let badValue = "no numbers here"
let badNumericString = badValue.numericString // nil

let anotherValue = "numbers 2 and text 4here 56"    
let anotherString = anotherValue.numericString // "2456"

Hope that helps.

pbodsk
  • 6,787
  • 3
  • 21
  • 51