请求匹配任意顺序双ETH地址的正则及文本ETH地址提取至数组方案
Got it, let's tackle your two ETH address-related tasks step by step. First, let's remember that a valid ETH address starts with 0x followed by exactly 40 hexadecimal characters (0-9, a-f, A-F).
1. Regex to Match Strings with Two ETH Addresses (Any Order)
If you need to check if a string contains at least two ETH addresses (in any order, can be same or different), use this regex:
^.*0x[a-fA-F0-9]{40}.*0x[a-fA-F0-9]{40}.*$
How it works:
^and$anchor the regex to match the entire string.*matches any character (except newlines) zero or more times0x[a-fA-F0-9]{40}is the core pattern for a valid ETH address- The pattern repeats twice to ensure at least two addresses are present, with any content in between or around them
If you need to enforce two distinct addresses (no duplicates), use this version with a negative lookahead:
^.*(0x[a-fA-F0-9]{40}).*(?!.*\1)0x[a-fA-F0-9]{40}.*$
(0x[a-fA-F0-9]{40})captures the first address into group 1(?!.*\1)is a negative lookahead that ensures the first captured address doesn't appear again before the second one
2. Extract ETH Addresses from Text into an Array
To pull all ETH addresses from a text message and store them in an array, you can use JavaScript's String.match() method with a global regex. Here's how it works with your example text:
// Your input text const invoiceText = "You have incoming invoice for 0xc7d688cb053c19ad5ee4f48c348958880537835f from 0xc7d688cb053c19ad5ee4f888848958dd0537835f with time spent 18 : 32 and remark test 1"; // Regex for ETH addresses, with global flag to match all occurrences const ethAddressRegex = /0x[a-fA-F0-9]{40}/g; // Extract addresses, default to empty array if no matches found const extractedAddresses = invoiceText.match(ethAddressRegex) || []; console.log(extractedAddresses); // Output: [ '0xc7d688cb053c19ad5ee4f48c348958880537835f', '0xc7d688cb053c19ad5ee4f888848958dd0537835f' ]
Notes:
- The
gflag in the regex tellsmatch()to find all matches instead of just the first one - If no addresses are found,
match()returnsnull, so we use|| []to ensure we always get an array (empty in that case) - This logic translates to most modern programming languages—for example, in Python you'd use
re.findall()instead ofmatch().
内容的提问来源于stack exchange,提问作者Jignesh Aakoliya
相关产品推荐
相关产品推荐

