使用python正则表达式仅提取第一个匹配项

时间:2015-01-19 11:51:56

标签: python regex string

我有一个字符串如下:

course_name = "Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)"

我想只提取'PGCPRM'或第一个括号内的值,并且有一个新的课程名称,如下所示:

course_name_new = "Post Graduate Certificate Programme in Retail Management (Online)"

3 个答案:

答案 0 :(得分:2)

您可以使用str.replace()

>>> course_name = "Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)"
>>> course_name.replace('(PGCPRM) ','')
'Post Graduate Certificate Programme in Retail Management (Online)'

编辑:如果您想在(Online)之前替换单词,则需要正则表达式和positive look-behind

>>> re.sub(r'(\(\w+\) )(?=\(Online\))','',course_name)
'Post Graduate Certificate Programme in Retail Management (Online)'

或者如果要删除第一个括号,请使用以下命令:

>>> re.sub(r'(\(\w+\) ).*?','',course_name)
'Post Graduate Certificate Programme in Retail Management (Online)'

对于提取,使用re.search

>>> re.search(r'(\(.*?\))',course_name).group(0)
'(PGCPRM)'

答案 1 :(得分:1)

非常简单:

In [8]: course_name
Out[8]: 'Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)'

In [9]: print re.sub('\([A-Z]+\)\s*', '', course_name)
Post Graduate Certificate Programme in Retail Management (Online)

In [17]: print re.search('\(([A-Z]+)\)\s*', course_name).groups()[0]
PGCPRM

答案 2 :(得分:1)

在第一个括号内提取值

>>> course_name = "Post Graduate Certificate Programme in Retail Management (PGCPRM) (Online)"
>>> x = re.search(r'\(.*?\)',course_name).group()
>>> x
'(PGCPRM)'

然后替换

>>> course_name.replace(x,'')
'Post Graduate Certificate Programme in Retail Management  (Online)'