使用regex从给定单词开始直到字符串结尾(包括换行符)提取字符串的一部分

2024-09-20 04:01:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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."?你知道吗


Tags: reyouhave字符areregexdoingsweet
3条回答

将句点放在character类中,在这里它是一个位置,它只匹配一个.字符,其他什么都不匹配。[...]表示该类中包含的任何文字字符。你知道吗

您想改用^{} configuration constant

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

或者,您应该将.放在character类之外,并在具有\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.']

马蒂恩的回答很好地解释了你所看到的行为。作为re.DOTALL(?:.\n)选项的替代方法,您可以使用以下内容:

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

因为\s表示“所有空白”;\S表示“除空白以外的任何内容”,所以将它们放在一个字符类中可以匹配任何字符,包括换行符。你知道吗

使用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.']

相关问题 更多 >