4

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 for Video-Conferencing
ABC UltraSharp 24 Monitor -QU2482Z

Output desired:

55
19
24
24
pogibas
  • 27,303
  • 19
  • 84
  • 117
Jayesh Nagar
  • 55
  • 1
  • 3
  • 1
    Possible duplicate of [Extract the first 2 Characters in a string](https://stackoverflow.com/questions/38750535/extract-the-first-2-characters-in-a-string) – SHS Jul 18 '18 at 12:59
  • No, it is not a dupe of [Extract the first 2 Characters in a string](https://stackoverflow.com/questions/38750535). Digits are not any chars. – Wiktor Stribiżew Jun 20 '19 at 10:41

4 Answers4

2

Solution using regex \\D to match non-digit characters and \\d{2} to match first two digits.

as.numeric(sub("\\D*(\\d{2}).*", "\\1", INPUT))
# [1] 55 19 24 24

data:

INPUT <- c("ABC Conference Room Monitor - Z5580J",
           "ABC 19 Monitor",
           "ABC 24 Monitor for Video-Conferencing",
           "ABC UltraSharp 24 Monitor -QU2482Z")
pogibas
  • 27,303
  • 19
  • 84
  • 117
1

Another solution:

strings <- c('ABC Conference Room Monitor - Z5580J','ABC 19 Monitor','ABC 24 Monitor for Video-Conferencing','ABC UltraSharp 24 Monitor -QU2482Z')
x <- as.numeric(gsub("\\D", "", strings))
as.numeric(substring(as.character(x*100), 1, 2))

[1] 55 19 24 24
Adamm
  • 2,150
  • 22
  • 30
1

Package stringr perhaps allows for the cleanest solution:

stringr::str_extract(string, "\\d{2}")
 "55" "19" "24" "24"
s_baldur
  • 29,441
  • 4
  • 36
  • 69
0

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
RLave
  • 8,144
  • 3
  • 21
  • 37