我有很多字符串,每个字符串都有以下格式:Ab_Cd-001234.txt
我想用 001234
替换它.我怎样才能在 R 中实现它?
最佳答案
使用 gsub
或 sub
你可以这样做 :
gsub('.*-([0-9]+).*','\\1','Ab_Cd-001234.txt')
"001234"
您可以使用
regexpr
与 regmatches
m <- gregexpr('[0-9]+','Ab_Cd-001234.txt')
regmatches('Ab_Cd-001234.txt',m)
"001234"
编辑 这 2 种方法是矢量化的,适用于字符串向量。
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"
关于string - 在 R 中提取混合数字和字符的字符串的数字部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15451251/