skip to Main Content

i want filter a string and get only the numbers, but the numbers with a count of characters for example 10, and the other numbers that dont meet the condition discard.
I try something like this:

let phoneAddress = "My phone number 2346172891, and my address is Florida 2234"

let withTrimming = phoneAddress.replacingOccurrences(of: "-", with: "")
.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789").inverted)

let withComponents = phoneAddress.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()

But this return

withTrimming = "2346172891, and my address is Florida 2234"
withComponents = "23461728912234"

When i only want the phone number string "2346172891", i dont know how i can resolve it.

2

Answers


  1. Use a regex such as d{10}:

    let string = "My phone number 2346172891, and my address is Florida 2234"
    
    do {
        let regexMatches = try NSRegularExpression(pattern: "\d{10}").matches(in: string, range: NSRange(string.startIndex..., in: string))
    
        // prints out all the phone numbers, one on each line
        for match in regexMatches {
            guard let range = Range(match.range, in: string) else { continue }
            print(string[range])
        }
    } catch {
       print(error)
    }
    
    // Output:
    // 2346172891
    

    Also, consider using NSDataDetector.

    Login or Signup to reply.
  2. You can use Regex

    let phoneAddress = "My phone number 2346172891, and my address is Florida 2234"
    
    let regex = (try? NSRegularExpression(pattern: "[0-9]{10}"))!
    let ranges = regex.matches(in: phoneAddress, range: NSRange(location: 0, length: phoneAddress.count))
    let phones: [String] = ranges.map {
        let startIndex = phoneAddress.index(phoneAddress.startIndex, offsetBy: $0.range.lowerBound)
        let endIndex   = phoneAddress.index(phoneAddress.startIndex, offsetBy: $0.range.upperBound)
        return String(phoneAddress[startIndex..<endIndex])
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search