0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonで正規表現を使う

Posted at

備忘録として

例1
import re

# ファイル名
filename = FILE_server01_team01_17.txt
# ファイル名が正規表現に引っかかるかどうか
filename_regex = re.compile.(r"FILE_(.*)_(\w+)_(\d+)\.txt")
# 一致した場合はTrue
search_file1 = filename_regex.match(filename)

Pythonで正規表現を使用する例

実例
import re

filename_regex = re.compile.(r"FILE_(.*)_(\w+)_(\d+)\.txt")  # ①引っかけたいファイルの正規表現
filenames      = [FILE_server01_team01_24.txt, FILE_server10_team02_25.txt, ...]  # ②ファイル名の配列

for filename in filenames:
    search_file1 = filename_regex.match(filename)
    # 該当しない場合
    if not search_file1:
        continue

    # ①にてグループ化した順番で取得できる
    server  = search_file1.group(1)    # (.*)
    team    = search_file1.group(2)    # (\w+)
    file_id = search_file1.group(3)    # (\d+)

    print(f"server:{server} team:{team} id:{file_id}")
0
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?