簡體   English   中英

如何使用正則表達式查找子字符串

[英]How to find a substring using regex

我在抓取 1000 篇路透社文章后得到的字符串如下所示:

<TEXT>&#2;
<TITLE>IF DOLLAR FOLLOWS WALL STREET JAPANESE WILL DIVEST</TITLE>
<AUTHOR>    By Yoshiko Mori</AUTHOR>
<DATELINE>    TOKYO, Oct 20 - </DATELINE><BODY>If the dollar goes the way of Wall Street,
Japanese will finally move out of dollar investments in a
serious way, Japan investment managers say.
 REUTER
&#3;</BODY></TEXT>

我想從這個字符串中提取標題、作者、日期和正文。 為此,我有以下正則表達式,但不幸的是,它不適用於正文部分。

try:
  body=re.search('<BODY>(.)</BODY>',example_txt).group(1)
except:
  body='NA'

這個 try-except 總是為 body 返回NA但適用於 title、author 和 dateline。 知道為什么嗎?

謝謝!

使用re.DOTALL以便. 也匹配換行符。

關於。 淘寶

制作'.' 特殊字符完全匹配任何字符,包括換行符; 沒有這個標志, '.' 將匹配除換行符以外的任何內容。

https://docs.python.org/3/library/re.html

您還需要*來匹配多個字符,而? 用於非貪婪匹配。

最后,我有一個預感,不太推薦try這里。 您可以改為檢查來自re.search的匹配對象是否為None

import re

example_txt = '''<TEXT>&#2;
<TITLE>IF DOLLAR FOLLOWS WALL STREET JAPANESE WILL DIVEST</TITLE>
<AUTHOR>    By Yoshiko Mori</AUTHOR>
<DATELINE>    TOKYO, Oct 20 - </DATELINE><BODY>If the dollar goes the way of Wall Street,
Japanese will finally move out of dollar investments in a
serious way, Japan investment managers say.
 REUTER
&#3;</BODY></TEXT>'''

m = re.search(r'<BODY>(.*?)</BODY>', example_txt, flags=re.DOTALL)
body = m.group(1) if m else 'NA'

print(body)

輸出:

Japanese will finally move out of dollar investments in a
serious way, Japan investment managers say.
 REUTER
&#3;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM