find bitcoin addresses in a string using regex in swift

To find a Bitcoin address using regular expressions in Swift, you can use the following code:

main.swift
let regex = try! NSRegularExpression(pattern: "(?<!\\w)(?:[13][a-km-zA-HJ-NP-Z1-9]{25,34})(?!\\w)", options: [])
let string = "This is a sample Bitcoin address: 1NvBGbD3cydJUbgEnKXrNzBP4zNy3w2Kc1"
let range = NSRange(location: 0, length: string.utf16.count)

if let match = regex.firstMatch(in: string, options: [], range: range) {
    let address = (string as NSString).substring(with: match.range)
    print(address) // This will print "1NvBGbD3cydJUbgEnKXrNzBP4zNy3w2Kc1"
} else {
    print("No Bitcoin addresses found.")
}
527 chars
11 lines

This regular expression pattern matches valid Bitcoin addresses that start with "1" or "3" and are 25-34 characters long. The (?<!\\w) and (?!\\w) parts are negative lookarounds that ensure the match is not part of a larger word.

Note that this regex pattern may not match all valid Bitcoin addresses and can potentially match some invalid ones. It is only a simple example to get you started.

gistlibby LogSnag