【问题标题】:Use of multiple regular parentheses to parse bbcode使用多个正则括号解析bbcode
【发布时间】:2014-06-07 04:49:01
【问题描述】:

我正在尝试使用正则表达式来解析 bbcode,到目前为止我可以使这个正则表达式正常工作

if re.search("(\[b\])", m, re.IGNORECASE):
    r = re.compile(r"\[b\](?P<name>.*?)\[\/b\]", re.IGNORECASE)
    m = r.sub(r'<b>\1</b>', m)

但是在这种情况下,我需要使用多个正则括号来捕获字体的样式和包含在字体 bbcode 中的内容,例如

[f color="#fff" ...]string[/f]

,我无法让它正常工作,因为输出总是这样结束

string</font>

这是我的正则表达式代码。我不知道我在这里做错了什么..

if re.search("(\[f .*?\])", m, re.IGNORECASE):
    r = re.compile(r"\[f (?P<tag>.*?)\](?P<name>.*?)\[\/f\]", re.IGNORECASE)
    m = r.sub(r'<font \g<tag>>\g<name></font>', m)

【问题讨论】:

    标签: python regex bbcode


    【解决方案1】:

    Daniel,看着你的模型代码,你正在寻找这样的东西:

    result = re.sub(r"\[f ([^\]]*)\]([^\[]*)\[/[^\]]*\]", r"<font \1>\2</font>", subject)
    

    使用[f color="#fff" ...]string[/f] 作为输入,输出为&lt;font color="#fff" ...&gt;string&lt;/font&gt;。当然,这不是有效的 html,但这正是您的代码试图做的事情,您可以从这里轻松地对其进行调整,以完全按照您的喜好进行替换。

    解释正则表达式

    \[                       # '['
    f                        # 'f '
    (                        # group and capture to \1:
      [^\]]*                 #   any character except: '\]' (0 or more
                             #   times)
    )                        # end of \1
    \]                       # ']'
    (                        # group and capture to \2:
      [^\[]*                 #   any character except: '\[' (0 or more
                             #   times)
    )                        # end of \2
    \[                       # '['
    /                        # '/'
    [^\]]*                   # any character except: '\]' (0 or more
                             # times)
    \]                       # ']'
    

    【讨论】:

      【解决方案2】:

      尝试使用这个包https://pypi.python.org/pypi/bbcode

      自己编写代码可能不是一个好主意。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-05
        • 2014-11-27
        • 2015-04-24
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        • 2015-12-30
        • 1970-01-01
        相关资源
        最近更新 更多