Converting text from jira to markdown

Viewed 201

I'm trying to convert text from Jira to markdown, but I run into a problem when trying to convert links and text color:

  • {color:red}text in red{color} to <span style="color:red">text in red</span>
  • [Google|http://google.com] to [Google](http://google.com)

The problem with color is that i want to leave color variable (this only would work for red color).

Here is my code, it works, but it's probably not the best way to solve the problem:

import re

conversion_dict = {
    r"\]": ")",
    r"\|": "](",
    r"{color:red}": "<span style=\"color:red\">",
    r"{color}": "</span>"
}


def format_text_from_jira(comment_body):
    for pattern in conversion_dict:
        comment_body = re.sub(pattern, conversion_dict[pattern], comment_body)
    return comment_body

Does anyone know better solution?

2 Answers

I would use re.sub with appropriate capture groups:

inp = "{color:red}text in red{color}"
regex = r'\{(.*?):(.*?)\}(.*?)\{\1\}'
output = re.sub(regex, r'<span style="\1:\2">text in red</span>', inp)
print(output)  # <span style="color:red">text in red</span>

For the color specific you can use 3 capture groups matching color with a backreference to color, a negated character class to match any char except the curly's and a non greedy match to match until the first occurrence of the matching closing part.

{(color):([^{}]+)}(.*?){\1}

Regex demo

And use the 3 capture groups in the replacement.

import re

regex = r"{(color):([^{}]+)}(.*?){\1}"
s = "{color:red}text in red{color}"
subst = '<span style="\\1:\\2\">\\3</span>)'
result = re.sub(regex, r'<span style="\1:\2">\3</span>', s)
print(result)

Output

<span style="color:red">text in red</span>

For the link you can use

\[([^][|]+)\|([^][]+)]

Regex demo

import re

regex = r"\[([^][|]+)\|([^][]+)]"
s = "[Google|http://google.com]"
subst = '<span style="\\1:\\2\">\\3</span>)'
result = re.sub(regex, r'[\1](\2)', s)
print(result)

Output

[Google](http://google.com)

Or you might make the link part a bit more specific

\[([^][|]+)\|(https?://[^][]+)]
Related