如何制作重新分割()包括

2024-09-30 04:27:42 发布

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

我有以下内容:

>>> x='STARSHIP_TROOPERS_INVASION_2012_LOCDE'
>>> re.split('_\d{4}',x)[0]
'STARSHIP_TROOPERS_INVASION'

我怎样才能把这一年包括在内?例如:

^{pr2}$

请注意,有数以万计的标题,我需要对每一个的年份进行划分。我不能在这里做一个普通的python split()。在


Tags: re标题split年份pr2starshipinvasiontroopers
3条回答

A more straightforward solution将使用^{}/^{}

m = re.search('_\d{4}', x)
print x[:m.end(0)]

如果您想坚持使用split(),可以use a lookbehind

^{pr2}$

(即使年份在字符串的末尾,也可以这样做,因为split()返回一个数组,其中包含原始字符串,以防找不到分隔符。)

您可以同时使用split()search(),假设您的字符串中有一个这样的日期。在

import re
x='STARSHIP_TROOPERS_INVASION_2012_LOCDE'
date=re.search('_\d{4}',x).group(0)
print(date)

给予

^{pr2}$

以及

print(re.split('_\d{4}',x)[0]+date)

给予

STARSHIP_TROOPERS_INVASION_2012

如果它总是相同的模式,那么为什么不呢:

>>> x = 'STARSHIP_TROOPERS_INVASION_2012_LOCDE'
>>> x[:x.rfind('_')]
'STARSHIP_TROOPERS_INVASION_2012'

对于原始正则表达式,由于未捕获匹配的组,因此它不是匹配项的一部分:

^{pr2}$

()将选择标记为captured group

Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the \number special sequence, described below. To match the literals '(' or ')', use ( or ), or enclose them inside a character class: [(] [)].

相关问题 更多 >

    热门问题