Open In App

Regular Expression to Validate a Bitcoin Address

Improve
Improve
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)



Last Updated : 10 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads