Ethereum Address Validation Using Regular Expressions - GeeksforGeeks (2024)

Last Updated : 09 Jan, 2024

Summarize

Comments

Improve

ETHEREUM address is a 40-character hexadecimal identifier that receives and sends Ether (ETH) and other Ethereum-based tokens. Ethereum addresses come in two main formats: the standard hexadecimal representation and the checksummed format.

Examples:

Input: 0x742d35Cc6634C0532925a3b844Bc454e4438f44e

Output: True

Explanation: This is a valid Ethereum address. It starts with “0x” and consists of 40 hexadecimal characters.

Input: 0x742d35cc6634c0532925a3b844bc454e4438f44e

Output: True

Explanation: This address is valid because it follows the correct format with “0x” at the beginning.

Input: 742d35Cc6634C0532925a3b844Bc454e4438f44e

Output: True

Explanation: Ethereum addresses are usually represented with “0x” at the start, but it’s not strictly required.

This address is valid because it consists of 40 hexadecimal characters, and the absence of “0x” doesn’t make it invalid.

Input: 0x123

Output: False

Explanation: This address is not valid because it lacks the required 40-character length.

Ethereum addresses must contain 40 hexadecimal characters after “0x.”

Input: 0123456789012345678901234567890

Output: True

Explanation: This address is valid because it contains 40 hexadecimal characters following “0x,”.

Correct Standard Hexadecimal Format

  1. Consists of 40 hexadecimal characters (0-9 and a-f).
  2. The “0x” prefix is optional but often included to denote that it’s a hexadecimal value.
  3. It only contains the characters 0-9 and a-f (lowercase).
  4. There are no spaces or other special characters in the address.
  5. It does not use the letters O, I, l, or the number 0 to avoid visual ambiguity.

Correct Checksummed Format (Mixed Case)

  1. Consists of 40 hexadecimal characters (0-9 and A-F or a-f).
  2. The “0x” prefix is optional but commonly used to denote that it’s a hexadecimal value.
  3. Characters in the address can be either uppercase (A-F) or lowercase (a-f).
  4. This mixed-case format is designed to provide more specificity and reduce the likelihood of typographical errors.
  5. There are no spaces or special characters in the address.
  6. It does not use the letters O, I, l, or the number 0 to avoid visual ambiguity.

Approach

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

Ethereum Address Regex Validation

Below is the regular expression (regex) pattern to validate Ethereum addresses in their standard hexadecimal format:

Regex:

regex : ^(0x)?[0-9a-fA-F]{40}$

Where,

^ and $: These anchors ensure that the entire string matches the pattern from start to finish.

(0x)?: The address may start with “0x” (optional) to denote it’s in hexadecimal format.

[0-9a-fA-F]{40}: This part matches exactly 40 characters, which should be hexadecimal characters (0-9 and A-F or a-f).

Below is the code implementation for the same:

C++

#include <iostream>

#include <regex>

class EthereumAddressValidator {

public:

static bool

isValidETHAddress(const std::string& address)

{

// Regex to check valid Ethereum address

std::regex regexPattern("^(0x)?[0-9a-fA-F]{40}$");

return std::regex_match(address, regexPattern);

}

static std::string printResult(bool valid)

{

return valid ? "True" : "False";

}

};

int main()

{

// Test Case 1:

std::string address1

= "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";

std::cout << EthereumAddressValidator::printResult(

EthereumAddressValidator::isValidETHAddress(

address1))

<< std::endl;

// Test Case 2:

std::string address3 = "742d35Cc6634C0532925a3b844Bc454"

"e4438f44e"; // Without "0x"

// prefix

std::cout << EthereumAddressValidator::printResult(

EthereumAddressValidator::isValidETHAddress(

address3))

<< std::endl;

// Test Case 3:

std::string address4 = "0x123"; // Invalid, too short

std::cout << EthereumAddressValidator::printResult(

EthereumAddressValidator::isValidETHAddress(

address4))

<< std::endl;

// Test Case 4:

std::string address5 = "0x12345678901234567890123456789"

"01234567890"; // Valid, maximum

// length

std::cout << EthereumAddressValidator::printResult(

EthereumAddressValidator::isValidETHAddress(

address5))

<< std::endl;

// Test Case 5:

std::string address6

= "0xabc123XYZ"; // Invalid, contains non-hex

// characters

std::cout << EthereumAddressValidator::printResult(

EthereumAddressValidator::isValidETHAddress(

address6))

<< std::endl;

return 0;

}

C

#include <regex.h>

#include <stdbool.h>

#include <stdio.h>

bool isValidETHAddress(const char* address)

{

regex_t regex;

int reti;

// Regex to check valid Ethereum address

const char* regexPattern = "^(0x)?[0-9a-fA-F]{40}$";

// Compile the regular expression

reti = regcomp(&regex, regexPattern, REG_EXTENDED);

if (reti) {

fprintf(stderr, "Could not compile regex\n");

return false;

}

// Execute the regular expression

reti = regexec(&regex, address, 0, NULL, 0);

// Free the memory used for the regex

regfree(&regex);

if (!reti) {

return true;

}

else if (reti == REG_NOMATCH) {

return false;

}

else {

char errorBuffer[100];

regerror(reti, &regex, errorBuffer,

sizeof(errorBuffer));

fprintf(stderr, "Regex match failed: %s\n",

errorBuffer);

return false;

}

}

void printResult(bool valid)

{

if (valid) {

printf("True\n");

}

else {

printf("False\n");

}

}

int main()

{

// Test Case 1:

const char* address1

= "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";

printResult(isValidETHAddress(address1));

// Test Case 2:

const char* address2

= "0x742d35cc6634c0532925a3b844bc454e4438f44e";

printResult(isValidETHAddress(address2));

// Test Case 3:

const char* address3 = "742d35Cc6634C0532925a3b844Bc454"

"e4438f44e"; // Without "0x"

// prefix

printResult(isValidETHAddress(address3));

// Test Case 4:

const char* address4 = "0x123"; // Invalid, too short

printResult(isValidETHAddress(address4));

// Test Case 5:

const char* address5 = "0x12345678901234567890123456789"

"01234567890"; // Valid, maximum

// length

printResult(isValidETHAddress(address5));

// Test Case 6:

const char* address6

= "0xabc123XYZ"; // Invalid, contains non-hex

// characters

printResult(isValidETHAddress(address6));

return 0;

}

Java

/*package whatever //do not write package name here */

import java.util.regex.*;

class EthereumAddressValidator {

public static boolean isValidETHAddress(String address)

{

// Regex to check valid Ethereum address

String regex = "^(0x)?[0-9a-fA-F]{40}$";

Pattern pattern = Pattern.compile(regex);

Matcher matcher = pattern.matcher(address);

return matcher.matches();

}

public static String print(boolean valid)

{

return valid ? "True" : "False";

}

public static void main(String[] args)

{

// Test Case 1:

String address1

= "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";

System.out.println(

print(isValidETHAddress(address1)));

// Test Case 2:

String address2

= "0x742d35cc6634c0532925a3b844bc454e4438f44e";

System.out.println(

print(isValidETHAddress(address2)));

// Test Case 3:

String address3

= "742d35Cc6634C0532925a3b844Bc454e4438f44e"; // Without "0x" prefix

System.out.println(

print(isValidETHAddress(address3)));

// Test Case 4:

String address4 = "0x123"; // Invalid, too short

System.out.println(

print(isValidETHAddress(address4)));

// Test Case 5:

String address5

= "0x1234567890123456789012345678901234567890"; // Valid, maximum length

System.out.println(

print(isValidETHAddress(address5)));

// Test Case 6:

String address6

= "0xabc123XYZ"; // Invalid, contains non-hex

// characters

System.out.println(

print(isValidETHAddress(address6)));

}

}

Python3

import re

class EthereumAddressValidator:

@staticmethod

def is_valid_eth_address(address):

# Regex to check valid Ethereum address

regex = r'^(0x)?[0-9a-fA-F]{40}$'

return bool(re.match(regex, address))

@staticmethod

def print_result(valid):

return "True" if valid else "False"

if __name__ == "__main__":

# Test Case 1:

address1 = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e"

print(EthereumAddressValidator.print_result(

EthereumAddressValidator.is_valid_eth_address(address1)))

# Test Case 2:

address2 = "0x742d35cc6634c0532925a3b844bc454e4438f44e"

print(EthereumAddressValidator.print_result(

EthereumAddressValidator.is_valid_eth_address(address2)))

# Test Case 3:

address3 = "742d35Cc6634C0532925a3b844Bc454e4438f44e" # Without "0x" prefix

print(EthereumAddressValidator.print_result(

EthereumAddressValidator.is_valid_eth_address(address3)))

# Test Case 4:

address4 = "0x123" # Invalid, too short

print(EthereumAddressValidator.print_result(

EthereumAddressValidator.is_valid_eth_address(address4)))

# Test Case 5:

address5 = "0x1234567890123456789012345678901234567890" # Valid, maximum length

print(EthereumAddressValidator.print_result(

EthereumAddressValidator.is_valid_eth_address(address5)))

# Test Case 6:

address6 = "0xabc123XYZ" # Invalid, contains non-hex characters

print(EthereumAddressValidator.print_result(

EthereumAddressValidator.is_valid_eth_address(address6)))

C#

using System;

using System.Text.RegularExpressions;

class EthereumAddressValidator {

static bool IsValidETHAddress(string address)

{

// Regex to check valid Ethereum address

string regexPattern = @"^(0x)?[0-9a-fA-F]{40}$";

Regex regex = new Regex(regexPattern);

return regex.IsMatch(address);

}

static string PrintResult(bool valid)

{

return valid ? "True" : "False";

}

static void Main()

{

// Test Case 1:

string address1

= "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";

Console.WriteLine(

PrintResult(IsValidETHAddress(address1)));

// Test Case 2:

string address2

= "0x742d35cc6634c0532925a3b844bc454e4438f44e";

Console.WriteLine(

PrintResult(IsValidETHAddress(address2)));

// Test Case 3:

string address3

= "742d35Cc6634C0532925a3b844Bc454e4438f44e"; // Without "0x" prefix

Console.WriteLine(

PrintResult(IsValidETHAddress(address3)));

// Test Case 4:

string address4 = "0x123"; // Invalid, too short

Console.WriteLine(

PrintResult(IsValidETHAddress(address4)));

// Test Case 5:

string address5

= "0x1234567890123456789012345678901234567890"; // Valid, maximum length

Console.WriteLine(

PrintResult(IsValidETHAddress(address5)));

// Test Case 6:

string address6

= "0xabc123XYZ"; // Invalid, contains non-hex

// characters

Console.WriteLine(

PrintResult(IsValidETHAddress(address6)));

}

}

Javascript

function isValidETHAddress(str) {

// Regex to check valid

// BITCOIN Address

let regex = new RegExp(/^(0x)?[0-9a-fA-F]{40}$/);

// 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";

}

}

// Test Case 1:

let address1 = "0x742d35Cc6634C0532925a3b844Bc454e4438f44e";

console.log(isValidETHAddress(address1));

// Test Case 2:

let address2 = "0x742d35cc6634c0532925a3b844bc454e4438f44e";

console.log(isValidETHAddress(address2));

// Test Case 3:

let address3 = "742d35Cc6634C0532925a3b844Bc454e4438f44e"; // Without "0x" prefix

console.log(isValidETHAddress(address3));

// Test Case 4:

let address4 = "0x123"; // Invalid, too short

console.log(isValidETHAddress(address4));

// Test Case 5:

let address5 = "0x1234567890123456789012345678901234567890"; // Valid, maximum length

console.log(isValidETHAddress(address5));

// Test Case 6:

let address6 = "0xabc123XYZ"; // Invalid, contains non-hex characters

console.log(isValidETHAddress(address6));

Output

True
True
False
True
False

Time Complexity: O(N)
Auxiliary Space: O(1) or O(N), depending on the implementation of the regular expression library and the specific input data.



rahul_chauhan_1998

Ethereum Address Validation Using Regular Expressions - GeeksforGeeks (2)

Improve

Next Article

Spring - MVC Regular Expression Validation

Please Login to comment...

Ethereum Address Validation Using Regular Expressions - GeeksforGeeks (2024)
Top Articles
Switching Your Savings Account Could Yield You 145 Times as Much Interest | The Motley Fool
Financial Self-Sufficiency: 7 Tips to Boost Yours
Elleypoint
Chatiw.ib
Dollywood's Smoky Mountain Christmas - Pigeon Forge, TN
Math Playground Protractor
Rainbird Wiring Diagram
Devotion Showtimes Near Mjr Universal Grand Cinema 16
Phenix Food Locker Weekly Ad
Corpse Bride Soap2Day
South Bend Tribune Online
Johnston v. State, 2023 MT 20
Theycallmemissblue
Mephisto Summoners War
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Cnnfn.com Markets
Los Angeles Craigs List
Labor Gigs On Craigslist
Craigslist Mpls Cars And Trucks
Bahsid Mclean Uncensored Photo
Bfg Straap Dead Photo Graphic
Hellraiser III [1996] [R] - 5.8.6 | Parents' Guide & Review | Kids-In-Mind.com
Jayah And Kimora Phone Number
Army Oubs
Wausau Marketplace
ZURU - XSHOT - Insanity Mad Mega Barrel - Speelgoedblaster - Met 72 pijltjes | bol
Ubg98.Github.io Unblocked
Healthier Homes | Coronavirus Protocol | Stanley Steemer - Stanley Steemer | The Steem Team
Azpeople View Paycheck/W2
South Bend Weather Underground
2015 Kia Soul Serpentine Belt Diagram
Goodwill Of Central Iowa Outlet Des Moines Photos
Combies Overlijden no. 02, Stempels: 2 teksten + 1 tag/label & Stansen: 3 tags/labels.
Robotization Deviantart
Kristy Ann Spillane
Vadoc Gtlvisitme App
Mastering Serpentine Belt Replacement: A Step-by-Step Guide | The Motor Guy
Calculator Souo
Wega Kit Filtros Fiat Cronos Argo 1.8 E-torq + Aceite 5w30 5l
Green Bay Crime Reports Police Fire And Rescue
Hair Love Salon Bradley Beach
Atlantic Broadband Email Login Pronto
Xemu Vs Cxbx
Regis Sectional Havertys
KM to M (Kilometer to Meter) Converter, 1 km is 1000 m
World History Kazwire
Los Garroberros Menu
Sara Carter Fox News Photos
Ts In Baton Rouge
Motorcycles for Sale on Craigslist: The Ultimate Guide - First Republic Craigslist
Mega Millions Lottery - Winning Numbers & Results
Uncle Pete's Wheeling Wv Menu
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6423

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.