Skip to main content
 首页 » 编程设计

python之使用正则表达式在python中的两个字符串之间提取字符串

2025年05月04日17zhengyun_ustc

"<>THIS is the place to stay at when visiting the historical area of Seattle.

Your right on the water front near the ferry's and great sea food hotel.

The breakfast was great. <>"

上面是我的示例文本。我想打印介于 <> 之间的字符串& <> .我希望我的输出没有换行符 \n ,像这样:

THIS is the place to stay at when visiting the historical area of Seattle. Your right on the water front near the ferry's and great sea food hotel.The breakfast was great.

我试过下面这段代码:

import re 
pattern = re.compile(r'\<>(.+?)\<>',re.DOTALL|re.MULTILINE) 
text = """<>THIS is the place to stay at when visiting the historical area of Seattle. 
 
Your right on the water front near the ferry's and great sea food hotel. 
 
The breakfast was great. 
<>""" 
results = pattern.findall(text) 
print results 

但我得到的结果是这样的:

["THIS is the place to stay at when visiting the historical area of Seattle.\n\nYour right on the water front near the ferry's and great sea food hotel.\n\nThe breakfast was great.\n"] 

但我不希望在结果字符串中有任何换行符。

请您参考如下方法:

在每个找到的匹配项上使用 .replace("\n", "")(使用理解)将任何换行符替换为空字符串。

参见 demo :

results = [x.replace("\n", "") for x in pattern.findall(text)] 
# => ["THIS is the place to stay at when visiting the historical area of Seattle.Your right on the water front near the ferry's and great sea food hotel.The breakfast was great."]