在 R 中提取混合数字和字符的字符串的数字部分 [英] Extract numeric part of strings of mixed numbers and characters in R
本文介绍了在 R 中提取混合数字和字符的字符串的数字部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有很多字符串,每个字符串都有以下格式:Ab_Cd-001234.txt
我想用 001234
替换它.我如何在 R 中实现它?
I have a lot of strings, and each of which tends to have the following format: Ab_Cd-001234.txt
I want to replace it with 001234
. How can I achieve it in R?
推荐答案
使用 gsub
或 sub
你可以这样做:
Using gsub
or sub
you can do this :
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"
EDIT 这 2 种方法是矢量化的,适用于字符串向量.
EDIT the 2 methods are vectorized and works for a vector of strings.
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"
这篇关于在 R 中提取混合数字和字符的字符串的数字部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文