How to write a regex for a sui address of length 64 eg. “0x02…5f331”?

89 views Asked by At

How to write a regex to be used in TypeScript for a Sui address as seen on the Sui explorer.
eg. the address "0xf821d3483fc7725ebafaa5a3d12373d49901bdfce1484f219daa7066a30df77d" as seen on https://suiexplorer.com/address/0xf821d3483fc7725ebafaa5a3d12373d49901bdfce1484f219daa7066a30df77d

It should not give a match if a user copied an adresss and some symbols where missing or when it is not a valid Sui address. eg. 2 missing symbols: "0xf821d3483fc7725ebafaa5a3d12373d491bdfce1484f219daa7066a30df77d"

I would like to use the regex in my TypeScript function. I did some trials on regex101.com but have troubles coming up with the correct regex.

1

There are 1 answers

1
Georges-Charles Brain On
0[xX][a-fA-F0-9]{64}

Explanation on regex101

Why not {1,64} to allow for 0x2, 0xdeed, etc.?

When users copy an address from their wallet or the sui explorer, it is always full-length, leading zeros are not trimmed. A shorter address likely means that the user deleted some characters by mistake. So, I want to check that all 64 characters are there for my use case. But for other use cases, {1,64} could make more sense (e.g. libraries).

You can also use the function isValidSuiAddress from the typescript SDK to test if a Sui address is correct.

Credit to Juzy for the original answer on Telegram.