How to recognise and extract alpha numeric characters in R

风流意气都作罢 提交于 2019-12-11 11:27:35

问题


I want to extract alphanumeric characters from a partiular sentence in R. I have tried the following:

aa=grep("[:alnum:]","abc")

.This should return integer(0),but it returns 1,which should not be the case as "abc" is not an alphanumeric. What am I missing here? Essentially I am looking for a function,that only searches for characters that are combinations of both alphabets and numbers,example:"ABC-0112","PCS12SCH" Thanks in advance for your help.


回答1:


[[:alnum:]] matches alphabets or digits. To match the string which contains the both then you should use,

x <- c("ABC", "ABc12", "--A-1", "abc--", "89=A")
grep("(.*[[:alpha:]].*[[:digit:]]|.*[[:digit:]].*[[:alpha:]])", x)
# [1] 2 3 5

or

which(grepl("[[:alpha:]]", x) & grepl("[[:digit:]]", x))
# [1] 2 3 5   


来源:https://stackoverflow.com/questions/26712380/how-to-recognise-and-extract-alpha-numeric-characters-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!