Skip to content

Useful Functions

agusmakmun edited this page Jul 21, 2021 · 5 revisions

These useful functions to find the images and usernames inside the markdown content, provides specialy for martor.

  1. function of markdown_find_images is useful if you want to retrieve all images inside the markdown content.
  2. function of markdown_find_mentions useful if you need to implement the notification system for user mentioned by another users, something like stackoverflow.
import re
from bs4 import BeautifulSoup
from martor.utils import markdownify


def markdown_find_images(markdown_text):
    """
    return list of image urls inside `markdown_text`.
    :param `markdown_text` is markdown text to find.

    example markdown text:
        Hello ![title](/path/to/image.png)
    provides for:
        jpeg|jpg|png|gif
    demo:
        https://regex101.com/r/uc3XfV/1
    """
    # patterns = r"[^(\s]+\.(?:jpeg|jpg|png|gif)(?=\b[+^\)])"
    patterns = r"[^(\s]+\.(?:jpeg|jpg|png|gif)(?=\))"
    return re.findall(patterns, markdown_text)


def markdown_find_mentions(markdown_text):
    """
    To find the users that mentioned
    on markdown content using `BeautifulShoup`.

    input  : `markdown_text` or markdown content.
    return : `list` of usernames.
    """
    mark = markdownify(markdown_text)
    soup = BeautifulSoup(mark, 'html.parser')
    return list(set(
        username.text[1::] for username in
        soup.findAll('a', {'class': 'direct-mention-link'})
    ))
Clone this wiki locally