2

I'm using two regular expressions:

    var myNumbers  = numbers.text?.stringByReplacingOccurrencesOfString("[^0-9]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil)


myNumbers  = myNumbers?.stringByReplacingOccurrencesOfString("^\\s*$", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil)

I'm removing non number characters and spaces but there a way to combine the regular expressions ?

user2924482
  • 8,380
  • 23
  • 89
  • 173
  • The second regex will never match anything unless the string contains exclusively whitespace characters. – vadian Jun 21 '16 at 16:59

2 Answers2

5
 var myNumbers  = numbers.text?.stringByReplacingOccurrencesOfString("[\\s\\D]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil)
Code
  • 6,041
  • 4
  • 35
  • 75
0

Building on Code's answer, the \s token captures all white space (tabs, spaces, new lines, etc.), and \D captures all digits.

let regex = "[\\s\\D]"

var myNumbers  = numbers.text?.stringByReplacingOccurrencesOfString(regex,
                                                         withString: "",
                                                            options: .RegularExpressionSearch,
                                                              range: nil)

Swift has automatic enum inference, so you don't need to write NSStringCompareOptions.RegularExpressionSearch. You can just write .RegularExpressionSearch, and the NSStringCompareOptions will be infered by the compiler from the signature of the function.

Community
  • 1
  • 1
Alexander
  • 59,041
  • 12
  • 98
  • 151