【问题标题】:StringsR - catch correct numbersStringsR - 捕捉正确的数字
【发布时间】:2021-02-02 23:59:36
【问题描述】:

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

【问题讨论】:

  • 您能否详细说明您的示例?你想达到什么目标?带有示例和输出。

标签: r regex stringr grepl


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    下面的代码可能就是你要找的。​​p>

    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的人。

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2017-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      相关资源
      最近更新 更多