从 R 中的 URL 中提取参数

Extracting parameter from URL in R

我想从一批 URL 中删除一个 'destinationId' 参数。

如果我有这样的URL:

https://urlaub.xxx.de/lastminute/europa/zypern-griechenland/?destinationId=45&semcid=de.ub

我如何提取 45? (destinationId=45)

我试图使用类似这样的东西,但我无法开始工作:

destinationIdParameter <- sub("[^0-9].*","",sub("*?\destinationId=","",url))

使用stringr你可以这样得到:

> library(stringr)
> address <- "https://urlaub.xxx.de/lastminute/europa/zypern-griechenland/?destinationId=45&semcid=de.ub"
> str_match(address, "destinationId=(.*?)&")[,2]
[1] "45"

如果(像我一样)您不习惯使用正则表达式,请使用 qdapRegex 包:

> library(qdapRegex)
> address <- "https://urlaub.xxx.de/lastminute/europa/zypern-griechenland/?destinationId=45&semcid=de.ub"
> ex_between(address, "destinationId=", "&")
[[1]]
[1] "45"

使用 base R,您可以通过几种方式提取数字。如果您确定此类网址中始终只有一个数字,则可以通过以下方式删除所有不是数字的内容:

> url <- "https://urlaub.xxx.de/lastminute/europa/zypern-griechenland/?destinationId=45&semcid=de.ub"
> gsub("[^0-9]", "", url)
[1] "45"

或者如果你想更安全并且想要 "destinationId=" 之后的特定数字而不是任何其他数字,那么你可以这样做:

destId <- regmatches(url, gregexpr("destinationId=\d+", url)) 
gsub("[^0-9]", "", destId)

如果您要从 url 中提取 destinationId 值,那么您可以这样做:

gsub(".+destinationId=(\d+).+", "\1", url)
  • 这里的\1指的是()里面的东西。
  • .+ 匹配任意字符 顺序。

有了基础 R,我们可以做:

url <- "https://urlaub.xxx.de/lastminute/europa/zypern-griechenland/?destinationId=45&semcid=de.ub"

extract <- function(url) {
  pattern <- "destinationId=\K\d+"
  (id <- regmatches(url, regexpr(pattern, url, perl = TRUE)))
}

print(extract(url))


或者(没有 perl = TRUE):

vanilla_extract <- function(url) {
  pattern <- "destinationId=([^&]+)"
  (regmatches(url, regexec(pattern, url))[[1]][2])
}

两者都产生

[1] "45"

我认为最好的方法是parameters()

library(urltools)
example_url <- "http://en.wikipedia.org/wiki/Aaron_Halfaker?debug=true"
parameters(example_url)