【问题标题】:Return all elements of a string except a substring in R [duplicate]返回字符串的所有元素,除了R中的子字符串[重复]
【发布时间】:2020-01-28 16:53:57
【问题描述】:

我正在尝试提取字符串中除指定子字符串之外的所有元素。我想提取除了单词 select 和 from 以及介于两者之间的所有内容之外的所有内容。我可以提取子字符串,但我不知道如何提取除子字符串之外的所有内容。

a <- "10 bananas select green apples from fruit where (select pears from apples order by fruit)"

#I can successfully extract the substrings using the following code, but I'm looking for the opposite: 
str_extract_all(a, "select.*?from")

#expected output
a<-"10 bananas fruit where ( apples order by fruit)"

【问题讨论】:

  • 只需将该模式替换为""。你只是想删除一个子字符串。使用gsub,或stringr::str_remove_all 内置作为替换字符串
  • 谢谢!我还需要从原始字符串中找到要保留的每个元素的位置。那件作品需要正则表达式吗?
  • 如果您仍在寻找相同的模式,那么可以。这是一个稍微不同的问题,但regexprstringr::str_locate_all 都会这样做。如果您环顾四周,其他 SO 帖子可能也会涉及该问题
  • 我需要所有非“select.*?from”的位置。我尝试了 str_locate_all(a, "[select.*?from]" 但它将表达式计算为单个字符而不是一个字符串。
  • 是的,因为通过将模式包装在 [] 中,您已经将模式更改为任何包含的字符。我不完全明白你在找什么,但这听起来像是一个单独的问题。如果您找不到处理该问题的 SO 帖子,请发布另一个问题(但请先查看 SO)

标签: r regex string


【解决方案1】:

我们可以使用str_remove

str_remove_all(a, "select.*?from")
#[1] "10 bananas  fruit where ( apples order by fruit)"

str_extract 根据模式提取子字符串。在这里,我们需要从字符串中移除模式子字符串并返回单个字符串

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多