使用正则表达式从给定单词开始直到字符串结尾(包含换行符的结尾)获取字符串的一部分

时间:2012-09-17 20:17:04

标签: python regex string

import re

stri = "Hello guys.\nHow are you doing?\nI hope you have sweet dreams tonight."
regex = re.compile("guys[.\n]*$")

print regex.findall(stri)

我知道正则表达式中的.可以是除换行符之外的任何字符,[xy]表示x或y,*后面的字符表示任意数量的该字符$ }表示字符串的结尾。那么"guys[.\n]*$"为什么不给我"guys.\nHow are you doing?\nI hope you have sweet dreams tonight."

3 个答案:

答案 0 :(得分:4)

您将句点放在一个字符类中,在一个的位置它只与.字符匹配,而不是其他任何内容。 [...]表示该类中包含的任何文字字符。

您想要使用re.DOTALL configuration constant代替:

regex = re.compile("guys.*$", re.DOTALL)

或者,您应该将.保留在角色类之外,并在具有\n换行符的组中使用它:

regex = re.compile("guys(?:.|\n)*$")

演示:

>>> import re
>>> stri = "Hello guys.\nHow are you doing?\nI hope you have sweet dreams tonight."
>>> regex = re.compile("guys.*$", re.DOTALL)
>>> print regex.findall(stri)
['guys.\nHow are you doing?\nI hope you have sweet dreams tonight.']

答案 1 :(得分:2)

Martijn的答案为您所看到的行为提供了一个很好的解释。作为re.DOTALL(?:.\n)选项的替代选项,您可以使用以下内容:

regex = re.compile(r"guys[\s\S]*$")

由于\s表示“所有空白”而\S表示“除空白之外的任何内容”,因此将它们放在一个字符类中将允许匹配包括换行符在内的任何字符。

答案 2 :(得分:0)

使用re.MULLTILINE,你应匹配线......

>>> regex = re.compile("guys.*",re.DOTALL|re.MULTILINE)
>>> regex.findall(stri)
['guys.\nHow are you doing?\nI hope you have sweet dreams tonight.']

/编辑:正如martjin指出我对多行

的看法不对
>>> regex = re.compile("guys.*",re.DOTALL)
>>> regex.findall(stri)
['guys.\nHow are you doing?\nI hope you have sweet dreams tonight.']