如何截取字符串?例如在 ATGAS_1121
中,我想删除所有在_
之前的内容。
使用正则表达式。在这种情况下,你可以使用gsub
:
gsub("^.*?_","_","ATGAS_1121")
[1] "_1121"
这个正则表达式匹配字符串的开头(^),任意字符(.)重复零次或多次(*),以及下划线(_)。 ? 使匹配“懒惰”,只匹配第一个下划线。该匹配替换为下划线。有关详细信息和参考,请参见?regex
。
您可以使用内置函数 strsplit 来实现此功能:
> s = "TGAS_1121"
> s1 = unlist(strsplit(s, split='_', fixed=TRUE))[2]
> s1
[1] "1121"
strsplit返回将字符串根据split参数分割的两部分作为一个列表同时返回。这可能不是你想要的结果,因此需要在调用之前使用unlist进行包装,然后对该数组进行索引,以便只返回向量中的第二个元素。
最后,应将fixed参数设置为TRUE,以指示分割参数不是正则表达式,而是字面匹配字符。
如果你是Tidyverse的粉丝,这里有一个stringr方案:
R> library(stringr)
R> strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
R> strings %>% str_replace(".*_", "_")
[1] "_1121" "_1432" "_1121"
# Or:
R> strings %>% str_replace("^[A-Z]*", "")
[1] "_1121" "_1432" "_1121"
如果s
是一个向量,以下是使用strsplit
的解决方案:
> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"
s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[1]))
- verbamour也许最直观的解决方案可能是使用 stringr
函数中的 str_remove
,与 str_replace
相比它甚至更容易,因为它只有一个参数而不是两个。
在你的例子中唯一棘手的部分是你想保留下划线,但这是可能的:你必须匹配正则表达式,直到它找到指定的字符串模式 (?=pattern)
。
看一个例子:
strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
strings %>% stringr::str_remove(".+?(?=_)")
[1] "_1121" "_1432" "_1121"
这里是使用 dplyr
包对数据框进行字符串分割的解决方案。
col1 = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
col2 = c("T", "M", "A")
df = data.frame(col1, col2)
df
col1 col2
1 TGAS_1121 T
2 MGAS_1432 M
3 ATGAS_1121 A
df<-mutate(df,col1=as.character(col1))
df2<-mutate(df,col1=sapply(strsplit(df$col1, split='_', fixed=TRUE),function(x) (x[2])))
df2
col1 col2
1 1121 T
2 1432 M
3 1121 A
gsub("^.*_","_","ATGAS_1121_xxx")
。现在已经修复。 - Richie Cotton