regex - R:查找数字是否在字符串范围内

标签 regex r string strsplit

我有一个字符串 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/

相关文章:

r - 如何在R中创建不同大小的空白向量

c - 我的函数填充字符串值

c# - 如何使用正则表达式在c#中提取文本字符串中方括号的内容

r - 如果不知道路径/源,如何在 Shiny 中播放音频文件?

r - 如何使用 ggplot2 创建堆叠直方图?

r - 如何使用 r 中的新管道对数据框中的行进行排序?

c++ - 从用户获取字符串中的多个单词的代码

c# - IP 地址的正则表达式

java - 正则表达式: match everything up to an optional capture group

Javascript:如何在 RegEx .exec 结果中获得多个匹配项