【问题标题】:Character Extraction from String从字符串中提取字符
【发布时间】:2013-02-09 16:40:07
【问题描述】:

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

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

我想回来:

asdasd segssddfge se

我试过了:

substr(a,1,".")

但它似乎不起作用。

有什么想法吗?

【问题讨论】:

  • 它是一个 csv 文件,所以应该只有一个“.”

标签: r


【解决方案1】:

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

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

【讨论】:

  • @Arun,忘记添加“fixed = TRUE”,这是我基于(可能是错误的)关于 OP 数据的假设而采取的方法。谢谢。
【解决方案2】:

使用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)

使用 subtrgregexpr(假设只有 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)

【讨论】:

    【解决方案3】:

    这里尝试使用gsub

    gsub(pattern='(.*)[.](.*)','\\1', c("asdasd.sss","segssddfge.sss","se.sss"))
    [1] "asdasd"     "segssddfge" "se"        
    

    【讨论】:

      猜你喜欢
      • 2011-07-21
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多