获取第一个空格前的字符

12

我正在寻找一种使用grep方法获取字符串中第一个空格前字符的方式。

由于我无法想出如何在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解决方案? - Tyler Rinker
grep 不是必须的...只是觉得这是自然的方式。 - ricardo
4个回答

16

或只是使用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) 的方法进行处理。 - kakarot

5
您可以使用qdapbeg2char(从字符串开头到特定字符)如下所示:
x <- c("the quick", "brown dogs were", "lazier than quick foxes")
library(qdap)
beg2char(x)
## [1] "the"    "brown"  "lazier"

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

0
使用 tidyverse 中的 stringr 包和 regex() 函数。
words %>% str_extract(regex('^\\S*'))
# [1] "the"    "brown"  "lazier"

正则表达式解析:

  • ^ 表示从行首开始匹配。
  • \S 匹配任何非空白字符(与 \s 相反)。我们在这里使用额外的转义反斜杠 this reason,所以它变成了 \\S
  • * 匹配前一个模式 0 到无限次。这意味着我们会继续寻找更多的非空白字符,直到找到一个空格为止。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接