Extract only first match using python regular expression

后端 未结 3 607
长发绾君心
长发绾君心 2021-01-28 05:50

I have a string as follows:

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

I want to extract only

3条回答
  •  死守一世寂寞
    2021-01-28 06:33

    You can use 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)'
    

    edit: if you want to replace the word before (Online) you need regex and a positive look-behind:

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

    Or if you want to remove the first parentheses use following :

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

    and for extract it use re.search :

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

提交回复
热议问题