0

我正在尝试为我的用户创建自定义语法来格式化一些 html

因此用户可以输入如下内容:

**some text here**
the some more text down here
**Another bunch of stuff**
then some other junk

and I get:

<h1>some text here</h2>
<p>the some more text down here</p>
<h1>Another bunch of stuff</h1>
<p>then some other junk</p>

并希望留出一些空间来弥补我需要的其他标签

编辑:所以我的问题是我将如何编写正则表达式函数来转换一些给定的文本并让它找到打开和关闭 ** 的每个实例并用适当的 or 标记替换它们。我有:进口重新

header_pattern = re.compile(r'(?P**)(?P.*)(?P**)', re.MULTILINE)

def format_headers(text):
    def process_match(m):
        return "<h2>%s</h2>" % m.group('header')

    new_text = header_pattern.sub(process_match, text)

    print new_text

但这只会抓住第一个 ** 和最后一个 ** 并忽略中间的那些。

4

2 回答 2

0

你有什么理由不能使用像 Cheetah 这样的简单模板语言并将逻辑构建到甚至处理程序中?Cheetah 将允许您创建一个模板对象,其中包含一组对操作 HTML 有用的方法。几周前,当我尝试使用 CherryPy 创建网页时,我遇到了类似的问题,在教程中我找到了 Cheetah 模板,它使编写表单变得更加容易!

于 2012-12-22T00:16:26.977 回答
0

使用一些标准溶液。像降价。它是最优选的。

要匹配您的标题字符串,请使用r'\*\*(.*?)\*\*'. 查看示例

>>> re.sub(r'\*\*(.*?)\*\*','<h1>\\1</h1>', '**some text here** and **another**')
'<h1>some text here</h1> and <h1>another</h1>'
于 2012-12-22T00:39:17.800 回答