我希望从一些字符串中提取前两个数字。 假设数据如下:
ABC Conference Room Monitor - Z5580J
ABC 19 Monitor
ABC 24 Monitor for Video-Conferencing
ABC UltraSharp 24 Monitor -QU2482Z
期望输出结果:
55
19
24
24
我希望从一些字符串中提取前两个数字。 假设数据如下:
ABC Conference Room Monitor - Z5580J
ABC 19 Monitor
ABC 24 Monitor for Video-Conferencing
ABC UltraSharp 24 Monitor -QU2482Z
期望输出结果:
55
19
24
24
\\D
匹配非数字字符,\\d{2}
匹配前两个数字。as.numeric(sub("\\D*(\\d{2}).*", "\\1", INPUT))
# [1] 55 19 24 24
数据:
INPUT <- c("ABC Conference Room Monitor - Z5580J",
"ABC 19 Monitor",
"ABC 24 Monitor for Video-Conferencing",
"ABC UltraSharp 24 Monitor -QU2482Z")
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
as.numeric(substr(gsub("\\D", "", strings),1,2))
呢? - moodymudskipper包stringr
可能提供了最干净的解决方案:
stringr::str_extract(string, "\\d{2}")
"55" "19" "24" "24"
stringr
的一个解决方案是:
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