从 R 中的 URL 路径中提取文件扩展名

Extract file extension from URL path in R

我尝试从

这样的 URL 中提取文件扩展名(如果存在)
> http://www.example.com/index.php?option=com&etc
> http://www.example.com/subpage1/subpage2/file.pdf

basename(URL)函数,我得到了文件。但是当我申请sub()时,我得到了这个

> sub(".*([.*])", "\1", basename(URL))
> php?option=com&etc
> .pdf

如何只检索扩展名(如果存在)?

我试过了file_ext(basename(URL))。它适用于第二个示例(当没有参数时)但它对第一个没有给出任何信息。

file_ext(basename(URL))
[1] ""

是否可以使用正则表达式来检索“.”之间的字符串?和“?”。

去掉?后面列出的所有参数,然后运行 file_ext:

tools::file_ext(sub("\?.+", "", URL))
#[1] "php" "pdf"

其中 URL 是:

URL <- c(
"http://www.example.com/index.php?option=com&etc",
"http://www.example.com/subpage1/subpage2/file.pdf"
)