Regular expression to extract the year from a string

后端 未结 5 822
盖世英雄少女心
盖世英雄少女心 2020-12-19 22:54

This should be simple but i cant seem to get it going. The purpose of it is to extract v3 tags from mp3 file names in Mp3tag.

I have these strings I want to extract

5条回答
  •  [愿得一人]
    2020-12-19 23:12

    You're almost there with your regular expression.

    What you really need is:

    \s\((\d{4})\)$
    

    Where:

    • \s is some whitespace
    • \( is a literal '('
    • ( is the start of the match group
    • \d is a digit
    • {4} means four of the previous atom (i.e. four digits)
    • ) is the end of the match group
    • \) is a literal ')'
    • $ is the end of the string

    For best results, put into a function:

    >>> def get_year(name):
    ...     return re.search('\s\((\d{4})\)$', name).groups()[0]
    ... 
    >>> for name in "Test String 1 (1994)", "34 Test String 2 (1995)", "Test (String) 3 (1996)":
    ...     print get_year(name)
    ... 
    1994
    1995
    1996
    

提交回复
热议问题