这将做到这一点:
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'
如果它比较容易阅读,您可以命名捕获组而不是使用第e \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"
d'oh!为什么我没有想到这一点。 +1 – mgilson 2013-04-30 02:38:44
here \ 1是(\ d +)匹配结果。对? – NamNamNam 2013-04-30 02:43:33
是的。有几件事要注意。正则表达式字符串开始处的'r'改变了这些字符串中'\'的含义,以使它们更易于阅读。捕获组括号被编号(通常)从左到右。所以如果你有're.sub(r'(\ d)(\ d)(\ d)',r'\ 2 \ 3 \ 1','123')'它会打印'231'你会得到它。 – dawg 2013-04-30 02:50:35