我有很多字符串,每个字符串往往具有以下格式:Ab_Cd-001234.txt
我想用它替换它001234.我怎样才能在R中实现它?
Ben*_*Ben 25
该stringr包有很多这种工作的方便快捷方式:
# input data following @agstudy
data <- c('Ab_Cd-001234.txt','Ab_Cd-001234.txt')
# load library
library(stringr)
# prepare regular expression
regexp <- "[[:digit:]]+"
# process string
str_extract(data, regexp)
Which gives the desired result:
[1] "001234" "001234"
Run Code Online (Sandbox Code Playgroud)
解释一下regexp:
[[:digit:]] 是0到9之间的任何数字
+ 表示前一项(在这种情况下,一个数字)将匹配一次或多次
此页面对于此类字符串处理也非常有用:http://en.wikibooks.org/wiki/R_Programming/Text_Processing
ags*_*udy 21
使用gsub或sub你可以这样做:
gsub('.*-([0-9]+).*','\\1','Ab_Cd-001234.txt')
"001234"
Run Code Online (Sandbox Code Playgroud)
你可以用regexpr与regmatches
m <- gregexpr('[0-9]+','Ab_Cd-001234.txt')
regmatches('Ab_Cd-001234.txt',m)
"001234"
Run Code Online (Sandbox Code Playgroud)
编辑这两个方法是矢量化的,适用于字符串向量.
x <- c('Ab_Cd-001234.txt','Ab_Cd-001234.txt')
sub('.*-([0-9]+).*','\\1',x)
"001234" "001234"
m <- gregexpr('[0-9]+',x)
> regmatches(x,m)
[[1]]
[1] "001234"
[[2]]
[1] "001234"
Run Code Online (Sandbox Code Playgroud)