sub 函式

  1. 範例:sub 函式將字串中找到的正規表示字串取代指定的字串。
    [dywang@deyu zzz]$ cat re3.py 
    #!/usr/bin/python3
    # coding: utf-8
    import re, sys
    
    str = sys.argv[1]
    mo1 = re.findall( r'c[aou]t', str, re.I)
    mo2 = re.sub( r'(c)([aou])(t)', r'\3\2\1', str)
    if mo1: print('1. findall :', mo1)
    if mo2: print('2. sub :', mo2)
    
  2. 執行結果:findall 找到三個匹配字串,sub 將找到的字串前後字元對調。
    [dywang@deyu zzz]$ ./re3.py "cat cot cut cxt"
    1. findall : ['cat', 'cot', 'cut']
    2. sub : tac toc tuc cxt