【问题标题】:Extracting parameter from URL in R从R中的URL中提取参数
【发布时间】:2018-04-03 10:56:14
【问题描述】:

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

如果我有这样的网址:

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

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

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

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

【问题讨论】:

标签: r regex substring gsub


【解决方案1】:

使用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"

【讨论】:

  • 谢谢!我真的很喜欢 qdapRegex 方法,因为正则表达式令人困惑。它的计算速度不如 gsub 解决方案 :(
【解决方案2】:

使用基数 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)

【讨论】:

    【解决方案3】:

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

    gsub(".+destinationId=(\\d+).+", "\\1", url)
    
    • 这里的\\1 指的是() 中的内容。
    • .+ 匹配任何字符 顺序。

    【讨论】:

      【解决方案4】:

      有了基础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"
      

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          猜你喜欢
          • 2015-05-30
          • 1970-01-01
          • 2012-11-19
          • 1970-01-01
          • 2021-06-15
          • 2021-10-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多