あるフリーランスエンジニアの色んなメモ!! ITスキル・ライフハックとか

Python:正規表現の全行マッチを実行する

実装例

import re


with open('/path/to/file') as f:
    # ファイルから全行を取得(str型)
    c = f.read()

    # re.MULTILINE または re.M の指定必須
    result = re.search(r'foo:[ ]+([^ ]+)\n', c, re.M)
    if result:
        # do something
        result.groups()

参考

7.2. re — Regular expression operations
https://docs.python.org/2.7/library/re.html#re.M
https://docs.python.org/2.7/library/re.html#re.search

comments powered by Disqus