Extract URL parameters and values in R

╄→尐↘猪︶ㄣ 提交于 2019-12-10 19:37:04

问题


We want to extract parameters and values from a given URL like

http://www.exemple.com/?a=1&b=2&c=3#def

Using xml2::url_parse we were able to Parse a url into its component pieces. However we still want to devide the query into elements using gsub matching regular expression:

([^?&=#]+)=([^&#]*)  

Desired output

a=1
b=2
c=3

回答1:


We can try

library(stringr)
matrix(str_extract_all(str1, "[a-z](?=\\=)|(?<=\\=)\\d+")[[1]], ncol=2, byrow=TRUE)

Or if we need the = also

 str_extract_all(str1, "[a-z]=\\d+")[[1]]
 #[1] "a=1" "b=2" "c=3"

data

str1 <- "http://www.exemple.com/?a=1&b=2&c=3#def"



回答2:


Use urltools package to parse URLs.

> u <- "http://www.exemple.com/?a=1&b=2&c=3#def"
> strsplit(urltools::parameters(u), "&")[[1L]]
[1] "a=1" "b=2" "c=3"
> urltools::param_get(u, "b")
  b
1 2


来源:https://stackoverflow.com/questions/34811595/extract-url-parameters-and-values-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!