Extract first N digits from a string

后端 未结 4 961
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 11:14

I want to extract just FIRST TWO DIGITS from some strings. Suppose the data is :

ABC Conference Room Monitor - Z5580J    
ABC 19 Monitor    
ABC 24 Monitor f         


        
4条回答
  •  情歌与酒
    2020-12-18 11:58

    One solution with stringr is:

    library(stringr)
    string <- str_extract_all("ABC Conference Room Monitor - Z5580J","\\(?[0-9,.]+\\)?")[[1]]
    # "\\(?[0-9,.]+\\)?" is the regex, extracts only numbers
    as.numeric(substr(string , 1,2)) # this selects the first two elements
    #as.numeric is optional
    

提交回复
热议问题