find bitcoin cash addresses in a string using regex in python

Here's a sample code that extracts Bitcoin Cash addresses from a string using regular expressions in Python:

main.py
import re

# Sample string containing Bitcoin Cash addresses
input_string = "You can send Bitcoin Cash to this address: bitcoincash:qpk068a25z73d5jk5e5jft0a3tq3xncxu58t0n0ur6"

# Regular expression to match Bitcoin Cash addresses
regex_pattern = r'(?i)\b(bitcoincash:)?(q|p)[a-z0-9]{41}\b'

# Find all matches of the regular expression in input_string
matches = re.findall(regex_pattern, input_string)

# Print the matches
for match in matches:
    print(match[1] + match[2:])
477 chars
15 lines

The output would be:

main.py
qpk068a25z73d5jk5e5jft0a3tq3xncxu58t0n0ur6
43 chars
2 lines

The regular expression used in this code matches strings that start with the string "bitcoincash:" (case-insensitive) or not, followed by either "q" or "p", and 41 alphanumeric characters. The alphanumeric characters should not be preceded or followed by any other alphanumeric characters to avoid matching false positives.

gistlibby LogSnag