2

我想用另一个字符拆分数字。

例子

输入:

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)and re.sub(r'\d(?=\S)', '\d ', string),但它不起作用。

4

2 回答 2

5

这将做到:

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"
于 2013-04-30T02:37:24.270 回答
2

这需要处理一种情况:

>>> re.sub(r'([a-zA-Z])(?=\d)',r'\1 ',s)
'he maybe have 212cm'

这会照顾另一个:

>>> re.sub(r'(?<=\d)([a-zA-Z])',r' \1',s)
'he maybe have212 cm'

希望比我有更多正则表达式经验的人能弄清楚如何将它们结合起来......

于 2013-04-30T02:27:32.223 回答