The Wayback Machine - https://web.archive.org/web/20240807192803/https://www.geeksforgeeks.org/regular-expression-to-validate-a-bitcoin-address/
Open In App

Regular Expression to Validate a Bitcoin Address

Last Updated : 10 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

BITCOIN is a digital currency. During the digital currency transaction, a BTC address is required to verify the legality of a bitcoin wallet a Bitcoin address is a long set of alphanumeric characters that contains numbers and letters. A Bitcoin address indicates the source or destination of a Bitcoin payment. A Bitcoin wallet is a digital wallet that allows you to send and receive Bitcoin.

Examples:

Input: 1RAHUEYstWetqabcFn5Au4m4GFg7xJaNVN2
Output: True
 
Input: 3J98t1RHT73CNmQwertyyWrnqRhWNLy
Output: True
 
Input: bc1qarsrrr7ASHy5643ydab9re59gtzzwfrah
Output: True

Input: b1qarsrrr7ASHy5643ydab9re59gtzzwfrah
Output: False
Explanation: Invalid BTC address as it starts with "b"
 
Input: 0J98t1RHT73CNmQwertyyWrnqRhWNLy
Output: False
Explanation: Invalid BTC address as it starts with 0.

Correct Format of  BITCOIN Address used:

  1. A BTC address is an identifier containing 26-35 alphanumeric characters.
  2. A BTC address starts with the numbers 1, 3, or bc1.
  3. It contains digits in the range of 0 to 9.
  4. It allows uppercase as well as lowercase alphabet characters.
  5. There is one exceptional point to be noted: The uppercase letter O, the uppercase letter I, the lowercase letter l, and the number 0 are not used to avoid visual ambiguity.
  6. It should not contain whitespaces and other special characters.

Approach:

  • This problem can be solved with the help of Regular Expressions.
  • Accept the BTC Address field as a string.
  • Use the above regex pattern to validate the string.
  • If the entered string will match the below-used regex then It will be a Valid BTC Address.
  • If the entered string will not match with the below-written regex then entered string will be an invalid BTC Address.

Regex:

“^(bc1|[13])[a-km-zA-HJ-NP-Z1-9]{25,34}$”

Where,

  • ^(bc1|[13]): This expression  will match whether the entered string starts with bc1 , 1 or 3.
  • [A – Z]: Matches a character having a character code between the two specified characters inclusive.
  • {25, 34} Quantifier: Matches the specified quantity of the previous token. {25, 34} will match 25 to 34. {3} will match exactly 3. {3,} will match 3 or more.
  • $: Denotes the end of the string.

Below is the code implementation of the above-used

C++




// C++ program to validate the
// BITCOIN Address using Regular
// Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate the
// BTC address
bool isValidBTCAddress(string str)
{
 
    // Regex to check valid
    // BTc address.
    const regex pattern(
        "^(bc1|[13])[a-km-zA-HJ-NP-Z1-9]{25,34}$");
 
    // If the str Code
    // is empty return false
    if (str.empty()) {
        return false;
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex_match(str, pattern)) {
        return true;
    }
    else {
        return false;
    }
}
 
string print(bool val)
{
    if (!val)
        return "False";
 
    return "True";
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "1RAHUEYstWetqabcFn5Au4m4GFg7xJaNVN2";
    cout << print(isValidBTCAddress(str1)) << endl;
 
    // Test Case 2:
    string str2 = "3J98t1RHT73CNmQwertyyWrnqRhWNLy";
    cout << print(isValidBTCAddress(str2)) << endl;
 
    // Test Case 3:
    string str3 = "bc1qarsrrr7ASHy5643ydab9re59gtzzwfrah";
    cout << print(isValidBTCAddress(str3)) << endl;
 
    // Test Case 4:
    string str4 = "b1qarsrrr7ASHy56439re59gtzzwfrah";
    cout << print(isValidBTCAddress(str4)) << endl;
 
    // Test Case 5:
    string str5 = "01qarsrrr7ASHy5643ydab9re59gtzzwfabc";
    cout << print(isValidBTCAddress(str5)) << endl;
 
    return 0;
}


Java




// Java program to validate the
// BITCOIN Address using Regular Expression
import java.util.regex.*;
 
class GFG {
 
    // Function to validate the
    //  BITCOIN Address
    public static boolean isValidBTCAddress(String str)
    {
 
        // Regex to check valid BTC address
        String regex
            = "^(bc1|[13])[a-km-zA-HJ-NP-Z1-9]{25,34}$";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the str
        // is empty return false
        if (str == null) {
            return false;
        }
 
        // Pattern class contains matcher() method
        // to find matching between given
        // str  using regular expression.
        Matcher m = p.matcher(str);
 
        // Return if the MICR Code
        // matched the ReGex
        return m.matches();
    }
 
    public static String print(boolean val)
    {
        if (!val)
            return "False";
 
        return "True";
    }
 
    // Driver Code.
    public static void main(String args[])
    {
 
        // Test Case 1:
        String str1 = "1RAHUEYstWetqabcFn5Au4m4GFg7xJaNVN2";
        System.out.println(print(isValidBTCAddress(str1)));
 
        // Test Case 2:
        String str2 = "3J98t1RHT73CNmQwertyyWrnqRhWNLy";
        System.out.println(print(isValidBTCAddress(str2)));
 
        // Test Case 3:
        String str3
            = "bc1qarsrrr7ASHy5643ydab9re59gtzzwfrah";
        System.out.println(print(isValidBTCAddress(str3)));
 
        // Test Case 4:
        String str4 = "b1qarsrrr7ASHy56439re59gtzzwfrah";
        System.out.println(print(isValidBTCAddress(str4)));
 
        // Test Case 5:
        String str5
            = "01qarsrrr7ASHy5643ydab9re59gtzzwfabc";
        System.out.println(print(isValidBTCAddress(str5)));
    }
}


Python3




# Python3 program to validate
# BITCOIN Address using Regular Expression
import re
 
# Function to validate
# BITCOIN Address
def isValidBTCAddress(str):
 
    # Regex to check valid BITCOIN Address
    regex = "^(bc1|[13])[a-km-zA-HJ-NP-Z1-9]{25,34}$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
 
# Test Case 1:
str1 = "1RAHUEYstWetqabcFn5Au4m4GFg7xJaNVN2"
print("Test Case 1:")
print(isValidBTCAddress(str1))
 
# Test Case 2:
str2 = "3J98t1RHT73CNmQwertyyWrnqRhWNLy"
print("\nTest Case 2:")
print(isValidBTCAddress(str2))
 
# Test Case 3:
str3 = "bc1qarsrrr7ASHy5643ydab9re59gtzzwfrah"
print("\nTest Case 3:")
print(isValidBTCAddress(str3))
 
# Test Case 4:
str4 = "b1qarsrrr7ASHy56439re59gtzzwfrah"
print("\nTest Case 4:")
print(isValidBTCAddress(str4))
 
# Test Case 5:
str5 = "01qarsrrr7ASHy5643ydab9re59gtzzwfabc"
print("\nTest Case 5:")
print(isValidBTCAddress(str5))


C#




// C# program to validate the
// BITCOIN Address
//using Regular Expressions
using System;
using System.Text.RegularExpressions;
class GFG
{
 
// Main Method
static void Main(string[] args)
{
 
    // Input strings to Match
    // BITCOIN Address
    string[] str={"1RAHUEYstWetqabcFn5Au4m4GFg7xJaNVN2","3J98t1RHT73CNmQwertyyWrnqRhWNLy","bc1qarsrrr7ASHy5643ydab9re59gtzzwfrah","b1qarsrrr7ASHy56439re59gtzzwfrah","01qarsrrr7ASHy5643ydab9re59gtzzwfabc"};
    foreach(string s in str) {
    Console.WriteLine( isValidBTCAddress(s) ? "true" : "false");
    }
    Console.ReadKey(); }
 
// method containing the regex
public static bool isValidBTCAddress(string str)
{
    string strRegex = @"^(bc1|[13])[a-km-zA-HJ-NP-Z1-9]{25,34}$";
    Regex re = new Regex(strRegex);
    if (re.IsMatch(str))
    return (true);
    else
    return (false);
}
}


Javascript




// Javascript program to validate
//BITCOIN Address using Regular Expression
 
// Function to validate the
// BITCOIN Address
function isValidBTCAddress(str) {
    // Regex to check valid
    // BITCOIN Address
    let regex = new RegExp(/^(bc1|[13])[a-km-zA-HJ-NP-Z1-9]{25,34}$/);
 
    // if str
    // is empty return false
    if (str == null) {
        return "false";
    }
 
    // Return true if the str
    // matched the ReGex
    if (regex.test(str) == true) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
let str1 = "1RAHUEYstWetqabcFn5Au4m4GFg7xJaNVN2";
console.log(isValidBTCAddress(str1));
 
// Test Case 2:
let str2 = "3J98t1RHT73CNmQwertyyWrnqRhWNLy";
console.log(isValidBTCAddress(str2));
 
// Test Case 3:
let str3 = "bc1qarsrrr7ASHy5643ydab9re59gtzzwfrah";
console.log(isValidBTCAddress(str3));
 
// Test Case 4:
let str4 = "b1qarsrrr7ASHy56439re59gtzzwfrah";
console.log(isValidBTCAddress(str4));
 
// Test Case 5:
let str5 = "01qarsrrr7ASHy5643ydab9re59gtzzwfabc";
console.log(isValidBTCAddress(str5));


Output

True
True
True
False
False

Time Complexity: O(N) for each test case, where N is the length of the given string. 
Auxiliary Space: O(1)



Similar Reads

How to validate MAC address using Regular Expression
Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with a hyphen (-) or colon(:). For example, 01-23-45-67
6 min read
How to validate an IP address using Regular Expressions in Java
Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.Examples: Input: str = "000.12.12.034" Output: True Input: str =
3 min read
How to validate Indian driving license number using Regular Expression
Given string str, the task is to check whether the given string is a valid Indian driving license number or not by using Regular Expression.The valid Indian driving license number must satisfy the following conditions: It should be 16 characters long (including space or hyphen (-)).The driving license number can be entered in any of the following f
7 min read
How to validate CVV number using Regular Expression
Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not have any alphabet or special characters. Examples: I
5 min read
Validate Corporate Identification Number (CIN) using Regular Expression
Given some Corporate Identification Number, the task is to check if they are valid or not using regular expressions. Rules for the valid CIN are: CIN is a 21 digits alpha-numeric code.It starts with either alphabet letter U or L.Next five characters are reserved for digits (0-9).Next two places are occupied by alphabet letters(A-Z-a-z).Next four pl
6 min read
How to validate a domain name using Regular Expression
Given string str, the task is to check whether the given string is a valid domain name or not by using Regular Expression.The valid domain name must satisfy the following conditions: The domain name should be a-z or A-Z or 0-9 and hyphen (-).The domain name should be between 1 and 63 characters long.The domain name should not start or end with a hy
6 min read
How to validate GST (Goods and Services Tax) number using Regular Expression
Given string str, the task is to check whether the given string is a valid GST (Goods and Services Tax) number or not using Regular Expression. The valid GST (Goods and Services Tax) number must satisfy the following conditions: It should be 15 characters long.The first 2 characters should be a number.The next 10 characters should be the PAN number
6 min read
How to validate HTML tag using Regular Expression
Given string str, the task is to check whether it is a valid HTML tag or not by using Regular Expression.The valid HTML tag must satisfy the following conditions: It should start with an opening tag (&lt;).It should be followed by a double quotes string or single quotes string.It should not allow one double quotes string, one single quotes string o
6 min read
How to validate IFSC Code using Regular Expression
Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be upper case alphabets.The fifth character should be
8 min read
How to validate MasterCard number using Regular Expression
Given string str, the task is to check whether the given string is a valid Master Card number or not by using Regular Expression. The valid Master Card number must satisfy the following conditions. It should be 16 digits long.It should start with either two digits numbers may range from 51 to 55 or four digits numbers may range from 2221 to 2720.In
7 min read
three90RightbarBannerImg