Remove all non-numeric characters from an NSString, keeping spaces

前端 未结 7 720
野性不改
野性不改 2021-01-07 21:57

I am trying to remove all of the non-numeric characters from an NSString, but I also need to keep the spaces. Here is what I have been using.

NS         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-07 22:41

    You could alter your first regex to include a space after the 9:

    In swift:

    var str = "test Test 333 9599 999";
    val strippedStr = str.stringByReplacingOccurrencesOfString("[^0-9 ]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil);
    // strippedStr = " 33 9599 999"
    

    While this leaves the leading space, you could apply a whitespace trimming to deal with that:

    strippedStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
    // strippedStr = "33 9599 999"
    

提交回复
热议问题