r - 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 中使用的字符串模式还不够。
解决方案
你是对的,你提供的正则表达式模式不足以提取你想要的数字。
以下代码可能是您正在寻找的。
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
。
推荐阅读
- javascript - 推送时覆盖值
- sql - 查询贷方和借方总和
- javascript - React SVG disappearing when component rerenders
- python - 尝试建立一个简单的库存管理程序
- android - Proguard 6 新的“-android”选项
- javascript - Javascript using a function Number() inside map() function to convert string to a number
- ios - 如何将 rawString 转换为 JSON 数组?
- django - Django class based view giving error
- spring-security - IFTTT Service disconnect does not clean up the Oauth Bearer token in my spring security auth server
- networking - Can a single server serve 2 different websites?