find bitcoin addresses in a string using regex in typescript

To find bitcoin addresses in a string using regex in TypeScript, you can use the following regular expression:

index.ts
const btcRegex = /(?:(?<=^)|(?<=[^\w]))[13][a-km-zA-HJ-NP-Z0-9]{25,34}(?:(?=$)|(?=[^\w]))/g;
93 chars
2 lines

This regex pattern looks for strings that start with either "1" or "3" followed by a string of characters from the set [a-km-zA-HJ-NP-Z0-9] that is between 25 and 34 characters long. To ensure that the regex pattern does not pick up false positives, it also requires that the string either starts at the beginning of the input string or is preceded by a non-word character, and that the string either ends at the end of the input string or is followed by a non-word character.

Here's an example of how you can use this regex pattern in TypeScript to find all of the bitcoin addresses in a string:

index.ts
const inputString = "Send 0.5 BTC to 1NPrfWgJfkANmd1jt88A141PjhiarT8d9W ASAP";
const btcRegex = /(?:(?<=^)|(?<=[^\w]))[13][a-km-zA-HJ-NP-Z0-9]{25,34}(?:(?=$)|(?=[^\w]))/g;

const result = inputString.match(btcRegex);
console.log(result); // outputs: [ '1NPrfWgJfkANmd1jt88A141PjhiarT8d9W' ]
291 chars
6 lines

In this example, the match method is used to find all of the matches of the btcRegex pattern in the inputString. The result is an array containing all of the bitcoin addresses that were found in the string.

gistlibby LogSnag