THIS is the place to stay at when visiting the historical area of Seattle. Your right on the wate-6ren">
gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:35:12 24 4
gpt4 key购买 nike

"<>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."]

关于python - 使用正则表达式在python中的两个字符串之间提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37809448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com