这将做到:
ins='''\
we spend 100year
today i'm200 pound
he maybe have212cm'''
for line in ins.splitlines():
line=re.sub(r'\s*(\d+)\s*',r' \1 ', line)
print line
印刷:
we spend 100 year
today i'm 200 pound
he maybe have 212 cm
同一行文本中的多个匹配的相同语法:
>>> re.sub(r'\s*(\d+)\s*',r' \1 ', "we spend 100year + today i'm200 pound")
"we spend 100 year + today i'm 200 pound"
捕获组(通常)从左到右编号,\number
指的是比赛中的每个编号组:
>>> re.sub(r'(\d)(\d)(\d)',r'\2\3\1','567')
'675'
如果更容易阅读,您可以命名您的捕获组,而不是使用\1 \2
符号:
>>> line="we spend 100year today i'm200 pound"
>>> re.sub(r'\s*(?P<nums>\d+)\s*',r' \g<nums> ',line)
"we spend 100 year today i'm 200 pound"