find bitcoin cash addresses in a string using regex in swift

To find Bitcoin Cash addresses in a string using regex in Swift, you can use the following code:

main.swift
let stringContainingBitcoinCashAddresses = "The Bitcoin Cash addresses are: bitcoincash:qp9c02vd6r8hg7r2r2qnf3q0ezrgahhvvg0n3ftj24, bitcoincash:qpmxrtxwn5twkderjgd4nc4huegj4a4ajgt8jsntun, and bitcoincash:qr0mhvz8edkdcjftmdrh0j7t8fa0jj8czsrmgnk6n9"

let regex = try? NSRegularExpression(pattern: "(bitcoincash:)?[qp][a-z0-9]{41}", options: [])

if let matches = regex?.matches(in: stringContainingBitcoinCashAddresses,
                                options: [],
                                range: NSRange(location: 0, length: stringContainingBitcoinCashAddresses.utf16.count)) {
    for match in matches {
        let btcAddress = (stringContainingBitcoinCashAddresses as NSString).substring(with: match.range)
        print("Bitcoin Cash address found: \(btcAddress)")
    }
}
783 chars
13 lines

This code will find all Bitcoin Cash addresses in the given string and print each address to the console. The regular expression pattern used here matches addresses that start with "bitcoincash:" or "q" or "p" followed by 41 alphanumeric characters.

gistlibby LogSnag