StringsR - 捕捉正确的数字

StringsR - catch correct numbers

我正在尝试基于 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 中使用的字符串模式还不够。

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

下面的代码可能就是您要找的。

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 的那些。

正则表达式模式可以用更简洁的方式表述:

numbers %>% 
  filter(grepl("^0\.1$|^0\.1\.", LEVEL))   # 0.1, 0.1.1, 0.1.2
numbers %>% 
  filter(grepl("^0\.11$|^0\.11\.", LEVEL)) # 0.11, 0.11.1
numbers %>% 
  filter(grepl("^0\.12$|^0\.12\.", LEVEL)) # 0.12, 0.12.1, 0.12.2