DebugPointer
Published on

Regex for Ethereum Wallet Address validation

Regex for Ethereum Wallet Address validation

A Ethereum address is a unique identifier that is used to send and receive Ethereum transactions. It is a string of letters and numbers that starts with the number "1" or "3". Here is an example of a Ethereum address- 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2. In this article let's understand how we can create a regex for a Ethereum Address and how regex can be matched for a Ethereum Address.

Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.

Conditions to match Ethereum Wallet Address

  • A ETH address is an identifier containing 40 alphanumeric characters.
  • A ETH address starts with 0x
  • It contains digits in the range of 0 to 9.
  • It allows uppercase (A-F) as well as lowercase alphabet (a-f) characters.
  • It should not contain whitespaces and other special characters.

Regex for checking if Ethereum Wallet Address is valid or not

Regular Expression-

/^0x[a-fA-F0-9]{40}$/gm

Test string examples for the above regex-

Input StringMatch Output
0xiuahbsndakjsddoes not match
0xeA0B9657892321121287128712BC78A89F989AAAmatches
0zzFGXD2E$does not match
0xBBAC6AABCFEBACEBCEABCEACB76767867676ACCCmatches

Here is a detailed explanation of the above regex-

/^0x[a-fA-F0-9]{40}$/gm

^ asserts position at start of a line
0x matches the characters 0x literally (case sensitive)
0 matches the character 0 with index 4810 (3016 or 608) literally (case sensitive)
x matches the character x with index 12010 (7816 or 1708) literally (case sensitive)
Match a single character present in the list below [a-fA-F0-9]
{40} matches the previous token exactly 40 times
a-f matches a single character in the range between a (index 97) and f (index 102) (case sensitive)
A-F matches a single character in the range between A (index 65) and F (index 70) (case sensitive)
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Hope this article was useful to check if a ethereum wallet address is valid or not.