Python正则表达式混淆

时间:2014-07-17 20:18:19

标签: python regex

有四个关键字:titleblogtagsstate
正在从各自的匹配中删除过多的关键字出现。

示例:
blog: blog state title tags and返回state title tags and而不是

blog state title tags and
sub函数在看到.+之后应该匹配blog:,因此我不知道为什么它将blog视为.+

正则表达式:

re.sub(r'((^|\n|\s|\b)(title|blog|tags|state)(\:\s).+(\n|$))', matcher, a)

代码:

def n15():
    import re
    a = """blog: blog: fooblog 
state: private
title: this is atitle bun
and text"""
    kwargs = {}
    def matcher(string):
        v = string.group(1).replace(string.group(2), '').replace(string.group(3), '').replace(string.group(4), '').replace(string.group(5), '')
        if string.group(3) == 'title':
            kwargs['title'] = v
        elif string.group(3) == 'blog':
            kwargs['blog_url'] = v
        elif string.group(3) == 'tags':
            kwargs['comma_separated_tags'] = v
        elif string.group(3) == 'state':
            kwargs['post_state'] = v
        return ''
    a = re.sub(r'((^|\n|\s|\b)(title|blog|tags|state)(\:\s).+(\n|$))', matcher, a)
    a = a.replace('\n', '<br />')
    a = a.replace('\r', '')
    a = a.replace('"', r'\"')
    a = '<p>' + a + '</p>'
    kwargs['body'] = a
    print kwargs

输出:

{'body': '<p>and text</p>', 'post_state': 'private', 'blog_url': 'foo', 'title': 'this is a bun'}

编辑:
期望输出:

{'body': '<p>and text</p>', 'post_state': 'private', 'blog_url': 'fooblog', 'title': 'this is atitle bun'}

1 个答案:

答案 0 :(得分:1)

replace(string.group(3), '')

将所有'blog'替换为''。

我建议不要尝试替换匹配字符串的所有其他部分,这很难做到,我建议在原始匹配中捕获您真正想要的字符串。

r'((^|\n|\s|\b)(title|blog|tags|state)(\:\s)(.+)(\n|$))'  

()周围有.+来捕获字符串的那一部分,然后

v = match.group(5)

matcher的开头。