首页 > 解决方案 > StringsR - 捕捉正确的数字

问题描述

我正在尝试基于 R 执行字符串过滤。我有多个层次结构,我需要将它们组合在一起

我准备了一个例子:


library(stringr)
library(tidyverse)

numbers <- tibble(LEVEL = c('0.1', '0.1.1', '0.1.2', '0.11', '0.12', '0.11.1', '0.12.1', '0.12.2'))



# Return also different values - first shall only contained: 0.1, 0.1.1, 0.1.2
numbers %>% 
  filter(grepl("^0.1.?", LEVEL))


# Second shall only contained: 0.11, 0.11.1
# Third shall only contained: 0.12, 0.12.1, 0.12.2

我在 grepl 中使用的字符串模式还不够。

标签: rregexstringrgrepl

解决方案


你是对的,你提供的正则表达式模式不足以提取你想要的数字。

以下代码可能是您正在寻找的。

numbers %>% 
filter(grepl("^[0]{1}\\.[1]{1}$|^[0]{1}\\.[1]{1}\\.", LEVEL))
# A tibble: 3 x 1
  LEVEL
  <chr>
1 0.1  
2 0.1.1
3 0.1.2

接下来我们只需要0.11, 0.11.1,即第一个之后的数字有两个 1,然后可能后面跟着另一个点。我们修改上面的代码以适应这种变化。

numbers %>% 
filter(grepl("^[0]{1}\\.(11){1}$|^[0]{1}\\.(11){1}\\.", LEVEL))

在这里,我们将11要隔离的数字放入一个组中,该组要查找恰好发生一次{1}。同样,我们可以写

numbers %>% 
filter(grepl("^[0]{1}\\.(12){1}$|^[0]{1}\\.(12){1}\\.", LEVEL))
# A tibble: 3 x 1
  LEVEL 
  <chr> 
1 0.12  
2 0.12.1
3 0.12.2

得到那些有模式的人12


推荐阅读