標籤:pattern 正則 字串 name def locale python re most return
1.
re.sub?Signature: re.sub(pattern, repl, string, count=0, flags=0)Docstring:Return the string obtained by replacing the leftmostnon-overlapping occurrences of the pattern in string by thereplacement repl. repl can be either a string or a callable;if a string, backslash escapes in it are processed. If it isa callable, it‘s passed the match object and must returna replacement string to be used.
參數說明:pattern模式字串,可以數字命名也可以name命名(\g<1>==\1)(?P<name>----------------\g<name>)
repl 替換的字串也可以是函數 string源串
count替換的次數
flag的值為:
re.I 使匹配對大小寫不敏感re.L 做本地化識別(locale-aware)匹配re.M 多行匹配,影響^和$re.S 使.匹配包括換行在內的所有字元re.U 根據Unicode字元集解析字元。這個標誌影響\w、\W、 \b和\Bre.X 該標誌通過給予你更靈活的格式以便你將Regex寫得更易於理解
2.執行個體
def replace_digit(m): ss = u‘〇一二三四五六七八九‘ index = int(m.group()) return ss[index]s = u‘1990年3月27日‘result = re.sub(u‘\d‘, replace_digit, s, count=4)print(result) # 一九九〇年3月27日
s = ‘2017-01-22‘s = re.sub(‘(\d{4})-(\d{2})-(\d{2})‘, r‘\2-\3-\1‘, s)print(s) # 01-22-2017
python re.sub