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)
我知道regex中的.
可以是除换行符以外的任何字符,[xy]
表示x或y,字符后面的*
表示该字符的任何数字,$
表示字符串的结尾。那为什么"guys[.\n]*$"
不给我"guys.\nHow are you doing?\nI hope you have sweet dreams tonight."
?你知道吗
将句点放在character类中,在这里它是一个位置,它只匹配一个
.
字符,其他什么都不匹配。[...]
表示该类中包含的任何文字字符。你知道吗您想改用^{} configuration constant :
或者,您应该将
.
放在character类之外,并在具有\n
换行符的组中使用它:演示:
马蒂恩的回答很好地解释了你所看到的行为。作为
re.DOTALL
或(?:.\n)
选项的替代方法,您可以使用以下内容:因为
\s
表示“所有空白”;\S
表示“除空白以外的任何内容”,所以将它们放在一个字符类中可以匹配任何字符,包括换行符。你知道吗使用re.MULLTILINE
,您应该在行上进行匹配…/编辑:正如martjin指出的,我对多行的看法是错误的
相关问题 更多 >
编程相关推荐