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

时间:2016-06-14 10:29:21

标签: python regex string

  

“<>这是参观历史区域时的住宿地点   西雅图。

     

你在靠近渡轮和海洋食物的水面上的权利   酒店。

     

早餐很棒。 <>“中

以上是我的示例文字。我想打印var bb = function(){ context.drawImage(imageurl, 10, 10); context.font = "40pt Calibri"; context.fillText("This is the text added", 20, 20); }; &amp;之间的字符串。 <>。我希望我的输出没有换行符<>,如下所示:

  

这是参观历史区的住宿地点   西雅图。您正好在靠近渡轮和大海的水滨   食物酒店。早餐很棒。

我尝试过以下代码:

\n

但我得到的结果如下:

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

但是我不想在结果字符串中添加任何换行符。

2 个答案:

答案 0 :(得分:4)

在每个找到的匹配项上使用.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."]

答案 1 :(得分:3)

只需替换您不想要的字符

e.g。

result_without_newline = str(result).replace('\n', '')

希望这有助于:)