javascript regex for extracting filename from Content-Disposition header

后端 未结 6 1592
忘掉有多难
忘掉有多难 2021-01-11 11:58

Content-disposition header contains filename which can be easily extracted, but sometimes it contains double quotes, sometimes no quotes and there are probably some other va

6条回答
  •  遥遥无期
    2021-01-11 12:34

    Disclaimer: the following answer only works with PCRE (e.g. Python / PHP), if you have to use javascript, use Robin's answer.


    This modified version of Robin's regex strips the quotes:

    filename[^;\n=]*=(['\"])*(.*)(?(1)\1|)
    
    filename        # match filename, followed by
    [^;=\n]*        # anything but a ;, a = or a newline
    =
    (['"])*         # either single or double quote, put it in capturing group 1
    (?:utf-8\'\')?  # removes the utf-8 part from the match
    (.*)            # second capturing group, will contain the filename
    (?(1)\1|)       # if clause: if first capturing group is not empty,
                    # match it again (the quotes), else match nothing
    

    https://regex101.com/r/hJ7tS6/28

    The filename is in the second capturing group.

提交回复
热议问题