pythonベース:正規表現


文書ディレクトリ
  • 正規表現
  • 単語、定義済み文字
  • 一括代替
  • 量詞(文字メタ文字文字セットの繰返し)
  • 貪欲と非貪欲
  • 境界
  • 単純例
  • マッチングからオブジェクト
  • を抽出する.
  • マッチング使用方法
  • groupオブジェクトの別名は
  • を使用します.
  • .split()および.sub()メソッド
  • その他補足
  • 正規表現
    単語、事前定義文字
  • .または外部のすべての文字
  • d一致数は[0-9]
  • に等しい
  • Dマッチング非数値同等[^0-9]
  • sすべての空白文字trfv
  • Sすべての空白文字[^trfv]
  • wアルファベット文字[a-zA-Z 0-9_]
  • Wアルファベット以外の文字[^a-zA-Z 0-9_]
  • 一括候補
    |e.g yes|noはyesとnoが一致することを示す
    りょうご
  • 文字?0または1を表す
  • 文字*0または複数の
  • を表す
  • 文字+1または複数を表す
  • 指定範囲:{n,m}n,mは範囲回数を表す
  • {n}n回
  • {n,}少なくともn回
  • {,m}最大n回
  • 貪欲と非貪欲
    貪欲(デフォルト):できるだけ最大範囲の結果を一致させる非貪欲:できるだけ最小範囲の結果を一致させるP.S div.*?div
    きょうかい
  • ^行頭
  • $行末
  • b単語境界
  • B非単語境界
  • A入力スイッチ
  • Z入力末尾
  • 単純なインスタンス
    一致からオブジェクトを抽出
    re.search(r'ab+c', 'ababc')
    re.search(r'(ab)+c', 'ababc')
    
    re.search(r'cent(re|er)', 'centre')
    
    re.search(r'(\w) \1', 'hello world') #  
    re.search(r'(\w) \1', 'hello hello') # hello hello    1   
    

    使用方法の一致
  • .findall
  • .match
  • .search
  • import re
    
    text = 'tom is 8 years old, make is 25 years old.'
    #     
    pattern = re.compile('\d+')
    #              
    re.findall(text, '\d+')
    # findall       list
    pattern.findall(text) # ['8', '25']
    # match
    pattern.match(text) #       
    pattern.match(text, 1) #  1     
    # search       
    pattern.search(text) 
    
    # search, mathch       
    m = pattern.search(text)
    m.group() #    .group(1)     
    #        
    m.group(1) # '8'
    m.group(2) # '25'
    #          
    m.start(1) # 7
    m.end(1) # 8
    #        
    m.groups() # ('8', '25')
    

    groupオブジェクトの別名使用
  • 宣言(モード)
  • 参照(?Pモード)
  • text = 'tom:98'
    pattern = re.compile(r'(?P\w+):(?P\d+)')
    m = pattern.search(text)
    m.group('name')
    m.group('score')
    

    .split()および.sub()メソッド
    .split()
    re.split(r'\W', 'good-morning') # ['good', 'morning]
    re.split(r'(-)', 'good-morning') # ['good', '-', 'morning]
    

    .sub()
    orders = 'ORD000
    ORD001
    ORD003'
    re.sub(r'\d+', '-', orders) # 'ORD-
    ORD-
    ORD-
    '
    text = 'beautiful is *better* than uglt' re.sub(r'\*(.*?)\*', '\g<1>', text) re.sub(r'\*(?P.*?)\*', '\g', text)

    その他の補足
    re.I #      
    re.M #     
    re.findall('hello', 'hello Hello', re.I)