R:匹配数字和字母

R: matching numbers and letters

如果我有这样的字符串 "F G123" 如何通过匹配字母获得 "FG" 并通过匹配数字获得 123

regexprregmatches 的一种方式:

x <- 'F G123' #string
x1 <- gsub(' ','',x) #remove spaces

m <- regexpr('[0-9]+', x1 ) #find indices of digits
> regmatches(x1 , m)        #use indices to fetch the digits
[1] "123"


m <- regexpr('[A-Z]+', x1 ) #find indices of Upper Case letters
> regmatches(x1 , m)        #use indices to fetch letters
[1] "FG"