简体   繁体   中英

Swift 5: Filter a string of characters, getting only the numbers with a condition

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.

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM