Swift:组合两个或更多正则表达式

时间:2016-06-21 16:51:18

标签: ios swift xcode7 nsregularexpression

我使用了两个正则表达式:

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


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

我删除非数字字符和空格但是有办法合并正则表达式吗?

2 个答案:

答案 0 :(得分:4)

 var myNumbers  = numbers.text?.stringByReplacingOccurrencesOfString("[\\s\\D]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil)

答案 1 :(得分:0)

Code's answer的基础上,\s令牌会捕获所有空格(制表符,空格,新行等),\D会捕获所有数字。

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

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

Swift具有自动枚举推理功能,因此您无需编写NSStringCompareOptions.RegularExpressionSearch。您只需编写.RegularExpressionSearch,编译器就会从函数的签名中感染NSStringCompareOptions