识别正则表达式中的新行

2024-04-28 07:42:26 发布

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

我想对麦克白的文本执行一些正则表达式

我的文字如下:

Scena Secunda.

Alarum within. Enter King Malcome, Donalbaine, Lenox, with
attendants,
meeting a bleeding Captaine.

  King. What bloody man is that? he can report,
As seemeth by his plight, of the Reuolt
The newest state

我的目的是把课文从回车到句号。你知道吗

我正在尝试这个正则表达式Enter(.?)*\.

但它没有显示匹配项。有人能修好我的regexp吗?你知道吗

我正在这个link里尝试


Tags: 文本with文字entermeetingkingwithinbleeding
1条回答
网友
1楼 · 发布于 2024-04-28 07:42:26

既然@Tushar没有解释你的正则表达式的问题,我决定解释一下。你知道吗

正则表达式-Enter(.?)*\.匹配单词Enter(字面意思),然后可选地匹配除换行符以外的任何字符0次或更多次,直到最后一个句点。你知道吗

问题是字符串在Enter和句点之间包含一个换行符。你也需要一个正则表达式模式来匹配新行。要强制.匹配换行符,可以使用DOTALL模式。但是,它不会得到预期的结果,因为*量词是贪婪的(将返回可能最长的子字符串)。你知道吗

所以,要得到从Enter到最近周期的子串,可以使用

Enter([^.]*)

this regex demo。如果不需要捕获组,请将其删除。你知道吗

IDEONE demo

import re
p = re.compile(r'Enter([^.]*)')
test_str = "Scena Secunda.\n\nAlarum within. Enter King Malcome, Donalbaine, Lenox, with\nattendants,\nmeeting a bleeding Captaine.\n\n  King. What bloody man is that? he can report,\nAs seemeth by his plight, of the Reuolt\nThe newest state"
print(p.findall(test_str)) # if you need the capture group text, or
# print(p.search(test_str).group()) # to get the whole first match, or
# print(re.findall(r'Enter[^.]*', test_str)) # to return all substrings from Enter till the next period

相关问题 更多 >