正则表达式使字符串从特定点开始

2024-09-30 08:28:12 发布

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

我必须使用正则表达式拆分字符串: 说Nikolaus Kopernikus -> 1473-1543

我尝试了下面的方法,但是它只提供了一个没有->的列表

我需要的是1473-1543年,最好是在清单['1473','1543']

import re

print ( re.split(r'->', 'Nikolaus Kopernikus -> 1473-1543'))

我想要一个正则表达式,使字符串从一个特定的符号开始,提前感谢了很多!你知道吗


Tags: 方法字符串importre列表符号splitprint
2条回答

如果要使用正则表达式:

import re
re.match('.*->[^\d]*(\d+)-(\d+)','Nikolaus Kopernikus -> 1473-1543').groups()
#output: ('1473', '1543')

如果需要列表而不是元组,请使用list函数。你知道吗

使用^{}

'Nikolaus Kopernikus -> 1473-1543'.split('->')[1].strip().split('-') # ['1473', '1543']

从文档中:

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

注意:我使用^{}在分割后删除空白。你知道吗

相关问题 更多 >

    热门问题