6

您将如何提取所有字符直到指定字符?例如,我想提取“。”之前的所有内容。(时期):

a<-c("asdasd.sss","segssddfge.sss","se.sss")

我想回来:

asdasd segssddfge se

我试过:

substr(a,1,".")

但它似乎不起作用。

有任何想法吗?

4

3 回答 3

7

这是一个非常基本的方法:

sapply(strsplit(a, "\\."), `[[`, 1)
# [1] "asdasd"     "segssddfge" "se"

还有一个:

sub(".sss", "", a, fixed = TRUE)
# [1] "asdasd"     "segssddfge" "se" 
## OR sub("(.*)\\..*", "\\1", a) 
## And possibly other variations
于 2013-02-09T16:43:21.657 回答
4

使用sub

# match a "." (escape with "\" to search for "." as a normal "." 
# means "any character") followed by 0 to any amount of characters
# until the end of the string and replace with nothing ("")
sub("\\..*$", "", a)

使用subtrand gregexpr(假设只有 1.并且向量内的所有字符串都有明确的匹配)。

# get the match position of a "." for every string in "a" (returns a list)
# unlist it and get the substring of each from 1 to match.position - 1
substr(a, 1, unlist(gregexpr("\\.", a)) - 1)
于 2013-02-09T16:45:17.783 回答
2

这里尝试使用gsub

gsub(pattern='(.*)[.](.*)','\\1', c("asdasd.sss","segssddfge.sss","se.sss"))
[1] "asdasd"     "segssddfge" "se"        
于 2013-02-09T17:00:33.093 回答