从字符串中删除 URL

标签 r string stringr

我有一个字符串向量— 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/

    相关文章:

    r - 错误延迟加载包 'devtools' 失败

    以逗号分隔的 Javascript 字符串

    java - 为什么我的应用程序在我单击某个按钮时崩溃?

    r - 如何使用正则表达式提取 case_when 语句中的特定字符串模式?

    regex - 匹配以已知模式开头的单词

    r - 如果上面的行在R中没有错误,请运行此行

    r - 添加两个列表的所有元素

    r - 从字符串中提取元素

    r - 在 R 中使用 randomForest 包进行预测

    ruby-on-rails - 如何在 ruby​​ on rails 应用程序中将数组输出转换为普通字符串