我需要从消息中包含来自文本的ETH地址的数组。
示例文字:
您有来自0xc7d688cb053c19ad5ee4f888848958dd0537835f的0xc7d688cb053c19ad5ee4f48c348958880537835f的收入发票,花费时间为18:32并且备注测试1
预期输出:
[
'0xc7d688cb053c19ad5ee4f48c348958880537835f,
'0xc7d688cb053c19ad5ee4f48c348958880537835f'
]
答案 0 :(得分:1)
使用regular expression /(0x[a-f0-9]{40})/g;
。这是一个快速的解决方案。
const regex = /(0x[a-f0-9]{40})/g;
const str = `You have incoming invoice for 0xc7d688cb053c19ad5ee4f48c348958880537835ffrom 0xc7d688cb053c19ad5ee4f888848958dd0537835f with time spent 18 : 32 and remark test 1`;
let m;
let result1 = [];
//Solution 1
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
result1.push(m[0]);
}
console.log(result1);
//Solution 2
let result2 = str.match(regex);
console.log(result2);
答案 1 :(得分:1)
使用match
跟随正则表达式(\b0x[a-f0-9]{40}\b)
:
let str = 'You have incoming invoice for 0xc7d688cb053c19ad5ee4f48c348958880537835f from 0xc7d688cb053c19ad5ee4f888848958dd0537835f with time spent 18 : 32 and remark test 1'
let resp = str.match(/(\b0x[a-f0-9]{40}\b)/g)
console.log(resp);