Extracting mentions from body | Typescript and Python | Hivemind

in Steem Dev9 months ago

Hello developers, I have been reading and comprehending the Python code of the Hivemind. I noticed that there are many reusable functions. Therefore, in this Hivemind series, I will attempt to share the useful functions provided by Hivemind in Python and convert them into Typescript. This conversion will enhance type handling and make them usable in Typescript or Javascript.

hivemind1.png

Today, we will examine the extract_mentions function. This function is utilized to retrieve the collection of all mentioned Steem users. The function employs a regular expression to identify and obtain the list of users within the body or given text.

GitHub

https://github.com/steemit/hivemind

Python

import re

def extract_mentions(body: str):
    regex = ('(?:^|[^a-zA-Z0-9_!#$%&*@/])'
             '(?:@)'
             '([a-zA-Z0-9][a-zA-Z0-9\\-.]{1,14}[a-zA-Z0-9])'
             '(?![a-z])')
    result = re.findall(
        regex, body)
    return {user.lower() for user in result}

Example (Python)

mentions = extract_mentions('''
Hello I am @faisalamin, how are you @rme, @blacks and @hungry-griffin
''')

print(mentions)

Typescript

function extract_mentions(body: string): string[] {
    const regex = /(?:^|[^a-zA-Z0-9_!#$%&*@/])(?:@)([a-zA-Z0-9][a-zA-Z0-9\-\.]{1,14}[a-zA-Z0-9])(?![a-z])/g

    const result = body.match(regex) || [];
    return result.map(user => user.toLowerCase().replace('@', '').trim());
}

Example (Typescript)

const mentions = extract_mentions(`
Hello I am @faisalamin, how are you @rme, @blacks and @hungry-griffin`)

console.log(mentions)



Best Regards @faisalamin

Download SteemPro Mobile

Coin Marketplace

STEEM 0.19
TRX 0.13
JST 0.029
BTC 58809.44
ETH 3151.28
USDT 1.00
SBD 2.43