[問題] 網址擷取特定字串

看板R_Language作者 (sunny_girl)時間3年前 (2020/11/21 01:19), 編輯推噓3(3014)
留言17則, 3人參與, 3年前最新討論串1/1
[問題類型]: 程式諮詢 [軟體熟悉度]: 入門 [問題敘述]: https://l.facebook.com/l.php?u=https%3A%2F%2Fwww.abc.com.tw%2Fday%2F1234%3Futm_source%3Dfacebook-abc%26utm_medium%3Dpost%26utm_campaign%3Dday%26utm_content%3Dlink-202010-happy%2F1234&h=AT0QK64y8zcRN3Of6strNOOhm2lESra4yGyR73iofDkVvVIYkPTmiVHee6RsQlfU1-delepwkeworiewj0rw2142_jifdks22313 1.想要擷取 %3Dlink 後面的 202010-happy 2.想要擷取 %2F 後面的 1234 試過用很原始的方式strsplit(),但切出來的東西與想像的不符合 想詢問各位R大神有沒有其他建議的語法QQ by對於正規式表達還是很不熟悉的R入門菜鳥 [關鍵字]: 特定字串擷取 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.171.49.216 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1605892764.A.66D.html

11/21 03:31, 3年前 , 1F
可以試試看用 % 符號來切割字串,再找你要的字串片段。另
11/21 03:31, 1F

11/21 03:31, 3年前 , 2F
外可以試著去查 regular expression ,以及grep 等 funct
11/21 03:31, 2F

11/21 03:31, 3年前 , 3F
ions,或是 stringr package 的用法
11/21 03:31, 3F

11/21 19:38, 3年前 , 4F
y <-regexpr('%3Dlink-(?:[a-zA-Z0-9\\-]+)%2F[0-9]+',x)
11/21 19:38, 4F

11/21 19:39, 3年前 , 5F
y值156 你打y還會顯示attr(,"match.length") 27
11/21 19:39, 5F

11/21 19:40, 3年前 , 6F
或者attributes(y)$match.length得到27 總長度 另外這裡
11/21 19:40, 6F

11/21 19:43, 3年前 , 7F
用了兩個'飾詞't1<-nchar('%3Dlink-')為8 %2F為3設給t2
11/21 19:43, 7F

11/21 19:48, 3年前 , 8F
啊要分兩次t<-regexpr('%3Dlink-(?:[a-zA-Z0-9\\-]+)%',x
11/21 19:48, 8F

11/21 19:51, 3年前 , 9F
substr(x, t+t1, t+attributes(t)$match.length-2)會得到
11/21 19:51, 9F

11/21 19:53, 3年前 , 10F
"202010-happy" 一樣抓它的長度t3<-nchar(...) 得到12
11/21 19:53, 10F

11/21 19:56, 3年前 , 11F
substr(x, y+attributes(t)$match.length+nchar(t2)+1,
11/21 19:56, 11F

11/21 19:57, 3年前 , 12F
y+attributes(y)$match.length-1) 就會抓到'1234'
11/21 19:57, 12F

11/21 20:00, 3年前 , 13F
抱歉一邊寫用不到t3但要分兩次,或抓一次用%2F做strsplit
11/21 20:00, 13F

11/22 00:30, 3年前 , 14F
str1 <- str_extract(string, '(?<=%3Dlink-).+(?=%2F)'
11/22 00:30, 14F

11/22 00:30, 3年前 , 15F
)
11/22 00:30, 15F

11/22 00:30, 3年前 , 16F
str2 <- str_extract(string, paste0('(?<=', str1, '%2
11/22 00:30, 16F

11/22 00:30, 3年前 , 17F
F).+(?=&)'))
11/22 00:30, 17F
文章代碼(AID): #1Vj_gSPj (R_Language)
文章代碼(AID): #1Vj_gSPj (R_Language)