【问题标题】:Converting text from jira to markdown将文本从 jira 转换为 markdown
【发布时间】:2021-06-19 05:47:41
【问题描述】:

我正在尝试将文本从 Jira 转换为 markdown,但在尝试转换链接和文本颜色时遇到了问题:

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

颜色的问题是我想保留颜色变量(这只适用于红色)。

这是我的代码,它可以工作,但它可能不是解决问题的最佳方法:

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

有人知道更好的解决方案吗?

【问题讨论】:

    标签: python regex replace markdown


    【解决方案1】:

    对于特定的颜色,您可以使用 3 个匹配 color 的捕获组和对颜色的反向引用,一个 negated character class 匹配除卷曲以外的任何字符,以及一个非贪婪匹配以匹配直到第一次出现匹配的结束部分.

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

    Regex demo

    并在替换中使用 3 个捕获组。

    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)
    

    输出

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

    您可以使用的链接

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

    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)
    

    输出

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

    或者你可以让链接部分更具体一些

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

    【讨论】:

      【解决方案2】:

      我会将re.sub 与适当的捕获组一起使用:

      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>
      

      【讨论】:

        猜你喜欢
        • 2020-08-27
        • 1970-01-01
        • 1970-01-01
        • 2011-03-12
        • 2022-06-15
        • 1970-01-01
        • 2010-10-20
        • 2019-09-23
        • 2012-09-29
        相关资源
        最近更新 更多