Skip to main content
 首页 » 编程设计

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

2025年05月04日20www_RR

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.\n你好吗?\n我希望你今晚有好梦。"?

请您参考如下方法:

你把句点放在一个字符类中,它是一个的地方,它将只匹配一个.字符,没有别的。 [...] 表示该类中包含的任何文字 字符。

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