我有一个字符串向量— myStrings
——在 R 中看起来像:
[1] download file from `http://example.com`
[2] this is the link to my website `another url`
[3] go to `another url` from more info.
哪里
another url
是一个有效的 http url 但 stackoverflow 不会让我插入多个 url 这就是为什么我要写 another url
相反。我想从 myStrings
中删除所有网址看起来像:[1] download file from
[2] this is the link to my website
[3] go to from more info.
我在
stringr
中尝试了很多功能包,但没有任何作用。
最佳答案
您可以使用 gsub
使用正则表达式来匹配 URL,
设置向量:
x <- c(
"download file from http://example.com",
"this is the link to my website http://example.com",
"go to http://example.com from more info.",
"Another url ftp://www.example.com",
"And https://www.example.net"
)
从每个字符串中删除所有 URL:
gsub(" ?(f|ht)tp(s?)://(.*)[.][a-z]+", "", x)
# [1] "download file from" "this is the link to my website"
# [3] "go to from more info." "Another url"
# [5] "And"
更新:最好能发布几个不同的 URL,以便我们知道我们正在使用什么。但我认为这个正则表达式适用于您在评论中提到的 URL:
" ?(f|ht)(tp)(s?)(://)(.*)[.|/](.*)"
上面的表达式解释了:
?
可选空间(f|ht)
匹配 "f"
或 "ht"
tp
匹配 "tp"
(s?)
可选匹配 "s"
如果有的话 (://)
匹配 "://"
(.*)
匹配每个字符(所有)直到 [.|/]
句点或正斜杠 (.*)
那么之后的一切我不是正则表达式的专家,但我认为我的解释是正确的。
注意:在 SO 答案中不再允许使用 url 缩短器,因此我在进行最近的编辑时被迫删除了一个部分。请参阅该部分的编辑历史记录。
关于从字符串中删除 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352448/