Rem*_*i.b 29 string grep r character gsub
我有一个包含随机字符的字符串列表,例如:
list=list()
list[1] = "djud7+dg[a]hs667"
list[2] = "7fd*hac11(5)"
list[3] = "2tu,g7gka5"
Run Code Online (Sandbox Code Playgroud)
我想知道unique()这个列表中至少有一次()存在哪些数字.我的例子的解决方案是:
解: c(7,667,11,5,2)
如果有人的方法不认为11是"十一"而是"一和一",那么它也会很有用.这种情况下的解决方案是:
解: c(7,6,1,5,2)
(我在相关主题上发现了这篇文章:从字符串向量中提取数字)
Aru*_*run 57
对于第二个答案,您可以使用gsub从字符串中删除不是数字的所有内容,然后按如下方式拆分字符串:
unique(as.numeric(unlist(strsplit(gsub("[^0-9]", "", unlist(ll)), ""))))
# [1] 7 6 1 5 2
Run Code Online (Sandbox Code Playgroud)
对于第一个答案,同样使用strsplit,
unique(na.omit(as.numeric(unlist(strsplit(unlist(ll), "[^0-9]+")))))
# [1] 7 667 11 5 2
Run Code Online (Sandbox Code Playgroud)
PS:不要命名你的变量list(因为有一个内置函数list).我把你的数据命名为ll.
A5C*_*2T1 16
这是另一个答案,这个gregexpr用于查找数字,并regmatches提取它们:
l <- c("djud7+dg[a]hs667", "7fd*hac11(5)", "2tu,g7gka5")
temp1 <- gregexpr("[0-9]", l) # Individual digits
temp2 <- gregexpr("[0-9]+", l) # Numbers with any number of digits
as.numeric(unique(unlist(regmatches(l, temp1))))
# [1] 7 6 1 5 2
as.numeric(unique(unlist(regmatches(l, temp2))))
# [1] 7 667 11 5 2
Run Code Online (Sandbox Code Playgroud)
# extract the numbers:
nums <- stri_extract_all_regex(list, "[0-9]+")
# Make vector and get unique numbers:
nums <- unlist(nums)
nums <- unique(nums)
Run Code Online (Sandbox Code Playgroud)
这是你的第一个解决方案
对于我将使用的第二个解决方案substr:
nums_first <- sapply(nums, function(x) unique(substr(x,1,1)))
Run Code Online (Sandbox Code Playgroud)
您可以使用?strsplit(如@ Arun的答案中提到的从矢量(字符串中)提取数字):
l <- c("djud7+dg[a]hs667", "7fd*hac11(5)", "2tu,g7gka5")
## split string at non-digits
s <- strsplit(l, "[^[:digit:]]")
## convert strings to numeric ("" become NA)
solution <- as.numeric(unlist(s))
## remove NA and duplicates
solution <- unique(solution[!is.na(solution)])
# [1] 7 667 11 5 2
Run Code Online (Sandbox Code Playgroud)
阿stringr与溶液str_match_all和管道运营商。对于第一个解决方案:
library(stringr)
str_match_all(ll, "[0-9]+") %>% unlist %>% unique %>% as.numeric
Run Code Online (Sandbox Code Playgroud)
第二种解决方案:
str_match_all(ll, "[0-9]") %>% unlist %>% unique %>% as.numeric
Run Code Online (Sandbox Code Playgroud)
(注意:我也称为列表ll)