【问题标题】:Get characters before first space在第一个空格之前获取字符
【发布时间】:2014-10-18 03:10:00
【问题描述】:

我正在寻找一种 gr​​ep 方法来获取字符串中第一个空格之前的字符。

我已经破解了以下函数,因为我不知道如何使用 R 中的 grep 类型命令来完成它。

有人可以提供grep 解决方案的帮助吗 - 如果有的话...

beforeSpace <- function(inWords) {
    vapply(inWords, function(L) strsplit(L, "[[:space:]]")[[1]][1], FUN.VALUE = 'character')
}
words <- c("the quick", "brown dogs were", "lazier than quick foxes")
beforeSpace(words)

R>          the quick         brown dogs were lazier than quick foxes 
              "the"                 "brown"                "lazier" 

如果有比grep(或我的函数beforeSpace)更好的方法,请告诉我。

【问题讨论】:

  • 为什么是 grep 解决方案?
  • grep 不是必须的.​​.....只是认为这将是自然的方式。

标签: r regex substring


【解决方案1】:

使用stringi

library(stringi) 
stri_extract_first(words, regex="\\w+")
#[1] "the"    "brown"  "lazier"

【讨论】:

    【解决方案2】:

    或者只是sub,感谢@flodel:

    sub(" .*", "", words)
    # and if the 'space' can also be a tab or other white-space:
    sub("\\s.*","",words)
    #[1] "the"    "brown"  "lazier"
    

    【讨论】:

    • 首先必须使用gsub('\u00A0',' ',words)之类的东西来处理任何不间断的空格
    【解决方案3】:

    您可以使用qdapbeg2char(字符串开头到特定字符)如下:

    x <- c("the quick", "brown dogs were", "lazier than quick foxes")
    library(qdap)
    beg2char(x)
    ## [1] "the"    "brown"  "lazier"
    

    【讨论】:

      猜你喜欢
      • 2012-02-06
      • 2023-04-01
      • 2011-07-31
      • 1970-01-01
      • 2015-06-06
      • 2016-04-26
      • 2021-07-27
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多