0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】文字列全体を正規表現で検索して一致する文字列を全て取得する関数

Last updated at Posted at 2020-03-02

文字列だけを取得したい場合は、re.findallで済みます。

target_text = "これまでに、人に感染する「コロナウイルス」は、7種類見つかっており、その中の一つが、昨年12月以降に問題となっている、いわゆる「新型コロナウイルス(SARS-CoV2)」です。 このうち、4種類のウイルスは、一般の風邪の原因の10~15%(流行期は35%)を占め、多くは軽症です。残りの2種類のウイルスは、2002年に発生した「重症急性呼吸器症候群(SARS)」や2012年以降発生している「中東呼吸器症候群(MERS)」です。 コロナウイルスはあらゆる動物に感染しますが、種類の違う他の動物に感染することは稀です。また、アルコール消毒(70%)などで感染力を失うことが知られています。"
keyword = "([0-9]+)"

results = re.findall(keyword, target_text)

# ['12', '2', '10', '15', '35', '2002', '2012', '70']

しかし、re.search()で取得できるmatchオブジェクトを全て取得したい場合に使える関数は用意されてません。
そこで、再帰的に文字列全体を検索する関数を書きます。

import re

def search_all(regrex, target, search_start_index=0, matches=None):

  if matches == None:
    matches = []

  match = re.search(regrex, target[search_start_index:])

  if match == None:
    return matches
  
  matches.append(match)
  
  return search_all(regrex, target, search_start_index + match.end() + 1, matches)
target_text = "これまでに、人に感染する「コロナウイルス」は、7種類見つかっており、その中の一つが、昨年12月以降に問題となっている、いわゆる「新型コロナウイルス(SARS-CoV2)」です。 このうち、4種類のウイルスは、一般の風邪の原因の10~15%(流行期は35%)を占め、多くは軽症です。残りの2種類のウイルスは、2002年に発生した「重症急性呼吸器症候群(SARS)」や2012年以降発生している「中東呼吸器症候群(MERS)」です。 コロナウイルスはあらゆる動物に感染しますが、種類の違う他の動物に感染することは稀です。また、アルコール消毒(70%)などで感染力を失うことが知られています。"
keyword = "([0-9]+)"

search_result_groups = search_all(keyword, target_text)

for item in search_result_groups:
  print(item.group())

# 12
# 2
# 10
# 15
# 35
# 2002
# 2012
# 70

追記

  • コメントでre.findall()についてご指摘頂き追記/編集しました。ありがとうございます。
  • コメントでデフォルト値を matches=[] と書くのはアンチパターンだとご指摘を頂き修正しました。ありがとうございます。
0
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?