我有一个字符串 s
,其中“子字符串”由竖线分隔。子字符串可能包含也可能不包含数字。我有一个测试字符串 n
包含一个数字,可能包含也可能不包含字母。请参见下面的示例。注意间距可以任意
我正在尝试删除 n
不在范围内或不完全匹配的所有子字符串。我知道我需要按 -
拆分,转换为数字,并将低/高与转换为数字的 n
进行比较。这是我的起点,但后来我陷入了从 unl_new
中获取最终好的字符串的困境。
s = "liquid & bar soap 1.0 - 2.0oz | bar 2- 5.0 oz | liquid soap 1-2oz | dish 1.5oz"
n = "1.5oz"
unl = unlist(strsplit(s,"\\|"))
unl_new = (strsplit(unl,"-"))
unl_new = unlist(gsub("[a-zA-Z]","",unl_new))
期望的输出:
"liquid & bar soap 1.0 - 2.0oz | liquid soap 1-2oz | dish 1.5oz"
我是不是完全走错了路?谢谢!
最佳答案
这里是一个使用 r-base 的选项;
## extract the n numeric
nn <- as.numeric(gsub("[^0-9|. ]", "", n))
## keep only numeric and -( for interval)
## and split by |
## for each interval test the condition to create a boolean vector
contains_n <- sapply(strsplit(gsub("[^0-9|. |-]", "", s),'[|]')[[1]],
function(x){
yy <- strsplit(x, "-")[[1]]
yy <- as.numeric(yy[nzchar(yy)])
## the condition
(length(yy)==1 && yy==nn) || length(yy)==2 && nn >= yy[1] && nn <= yy[2]
})
## split again and use the boolean factor to remove the parts
## that don't respect the condition
## paste the result using collapse to get a single character again
paste(strsplit(s,'[|]')[[1]][contains_n],collapse='')
## [1] "liquid & bar soap 1.0 - 2.0oz liquid soap 1-2oz dish 1.5oz"
关于regex - R:查找数字是否在字符串范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464067/