【问题标题】:Python: replace some tags to html tags in stringPython:将一些标签替换为字符串中的html标签
【发布时间】:2014-02-05 13:54:12
【问题描述】:

我有一些文字,例如:

我的文字\b最好的\b

但我不能做这个\任务因为

这是 fu** 正则表达式?和其他文字

如何将这些标签替换为 HTML 标签,如下所示:

我的文字最好

但我无法完成这项任务,因为

这是 fu** 正则表达式?和其他文字

成对标记\b,但不成对标记\a,并且必须只包含下一个单词。

【问题讨论】:

    标签: python html regex


    【解决方案1】:

    使用两个单独的替换:

    sample = re.sub(r'\\b(.*?)\\b', r'<h5>\1</h5>', sample)
    sample = re.sub(r'\\a(\s*\w+)', r'<a href="#task">\1</a>', sample)
    

    演示:

    >>> import re
    >>> sample = '''\
    ... My text \\b the best \\b
    ... but i cant do this \\a task because
    ... this is fu** regex? And other text
    ... '''
    >>> sample = re.sub(r'\\b(.*?)\\b', r'<h5>\1</h5>', sample)
    >>> sample = re.sub(r'\\a(\s*\w+)', r'<a href="#task">\1</a>', sample)
    >>> sample
    'My text <h5> the best </h5>\nbut i cant do this <a href="#task"> task</a> because\nthis is fu** regex? And other text\n'
    >>> print sample
    My text <h5> the best </h5>
    but i cant do this <a href="#task"> task</a> because
    this is fu** regex? And other text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多