我要用另一个字符分割数字。
例子
输入:
we spend 100year
输出:
we speed 100 year
输入:
today i'm200 pound
输出
today i'm 200 pound
输入:
he maybe have212cm
输出:
he maybe have 212 cm
我试过
re.sub(r'(?<=\S)\d', ' \d', string)
和re.sub(r'\d(?=\S)', '\d ', string)
,但都没用。 最佳答案
这样做:
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"
关于python - Python正则表达式:如何将数字与非数字匹配?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16291217/