Python正则表达式:如何将数字与非数字匹配?

2024-10-06 07:56:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把数字和另一个字符分开。你知道吗

示例

输入:

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),但都没用。你知道吗


Tags: re示例todaystring数字字符yearwe
2条回答

这样就可以了:

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"

这需要处理一个案例:

>>> 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'

希望有人有更多的regex经验比我能想出如何结合他们。。。你知道吗

相关问题 更多 >