正则表达式,在多行字符串中的两个模式之间进行匹配

时间:2014-09-10 22:45:34

标签: python regex

我有一个多行字符串,我想要一个正则表达式从两个模式之间抓取一些东西。例如,我在这里尝试匹配标题和日期之间的所有内容

例如:

s ="""\n#here's a title\n\nhello world!!!\n\nPosted on 11-09-2014 02:32:30"""
re.findall(r'#.+\n',s)[0][1:-1] # this grabs the title
Out: "here's a title"
re.findall(r'Posted on .+\n',s)[0][10:-1] #this grabs the date
Out: "11-09-2014 02:32:30"
re.findall(r'^[#\W+]',s) # try to grab everything after the title
Out: ['\n'] # but it only grabs until the end of line

5 个答案:

答案 0 :(得分:1)

>>> s = '''\n#here's a title\n\nhello world!!!\n\nPosted on 11-09-2014 02:32:30'''
>>> m1 = re.search(r'^#.+$', s, re.MULTILINE)
>>> m2 = re.search(r'^Posted on ', s, re.MULTILINE)
>>> m1.end()
16
>>> m2.start()
34
>>> s[m1.end():m2.start()]
'\n\nhello world!!!\n\n'

不要忘记检查m1m2是否不是None

答案 1 :(得分:1)

>>> re.findall(r'\n([^#].*)Posted', s, re.S)
['\nhello world!!!\n\n']

如果你想避免换行:

>>> re.findall(r'^([^#\n].*?)\n+Posted', s, re.S + re.M)
['hello world!!!']

答案 2 :(得分:1)

您可以使用一个正则表达式匹配所有内容。

>>> s = '''\n#here's a title\n\nhello world!!!\n\nPosted on 11-09-2014 02:32:30'''
>>> re.search(r'#([^\n]+)\s+([^\n]+)\s+\D+([^\n]+)', s).groups()
("here's a title", 'hello world!!!', '11-09-2014 02:32:30')

答案 3 :(得分:0)

您应该使用括号使用组匹配:

    result = re.search(r'#[^\n]+\n+(.*)\n+Posted on .*', s, re.MULTILINE | re.DOTALL)
    result.group(1)

此处我使用了search,但如果相同的字符串可能包含多个匹配项,您仍然可以使用findall ...

如果要捕获标题,内容和日期,可以使用多个组:

    result = re.search(r'#([^\n]+)\n+(.*)\n+Posted on ([^\n]*)', s, re.MULTILINE | re.DOTALL)
    result.group(1) # The title
    result.group(2) # The contents
    result.group(3) # The date

在同一个正则表达式中捕获所有3个比在每个部分中使用一个要好得多,特别是如果您的多行字符串可能包含多个匹配项(其中“同步”您的个人findall结果可能很容易导致错误的标题 - 内容日期组合)。

如果您打算使用这个正则表达式,请考虑为性能编译一次:

    regex = re.compile(r'#([^\n]+)\n+(.*)\n+(Posted on [^\n]*)', re.MULTILINE | re.DOTALL)
    # ...
    result = regex.search(s)
    result = regex.search('another multiline string, ...')

答案 4 :(得分:0)

将组匹配与非贪婪搜索(。*?)一起使用。并为该组命名以便于查找。

>>> s = '\n#here\'s a title\n\nhello world!!!\n\nPosted on 11-09-2014 02:32:30'
>>> pattern = r'\s*#[\w \']+\n+(?P<content>.*?)\n+Posted on'
>>> a = re.match(pattern, s, re.M)
>>> a.group('content')
'hello world!!!'