【问题标题】:R-- Extract specific text and the subsequent text/numbersR-- 提取特定文本和随后的文本/数字
【发布时间】:2021-05-26 19:27:15
【问题描述】:

我有一个包含文本字符串的列,我想提取的不仅是一个特定的字符串,还有这个指定字符串后面的字符串或数字。有什么好的解决方案?

在下面的示例中 - 我想创建一个列“extract”和str_extract 单词“lot”和“unit”,并且还提取此文本后面的后续数字。

id notes extract
1 LOT 56, STRATA TITLE, 56/SP77100, LOT 56
2 18/SP71866, COMMERCIAL, 17/SP71866, lot 18 lot 18
3 unit 9; 3R/PS732002 unit 9
4 V1602 F63, Section 8 Block 68 Unit 3 Unit 3

查看了很多正则表达式代码,但对于如何从指定的目标文本字符串中提取后续值没有任何帮助。

到目前为止,从另一个 StackOverflow 问题中尝试过这个-

 result <- table %>% 
  mutate(extract = str_extract(notes, "(?lot\\s)\\W\\s?\\d+\\")) %>%
  mutate(lot = str_squish(lot)) 

【问题讨论】:

  • 如果我的回答没有解决您的问题,请考虑更新问题。

标签: r regex dplyr


【解决方案1】:

你可以使用

str_extract(notes, "(?i)\\b(?:lot|unit)\\W*\\d+")

请参阅regex demo。

详情

  • (?i) - 不区分大小写的标志
  • \b - 单词边界
  • (?:lot|unit) - lot 或 unit
  • \W* - 任何零个或多个非单词字符
  • \d+ - 一位或多位数字。

R 测试:

library(dplyr)
library(stringr)
df <- data.frame(notes=c("LOT 56, STRATA TITLE, 56/SP77100,","18/SP71866, COMMERCIAL, 17/SP71866, lot 18","unit 9; 3R/PS732002", "V1602 F63, Section 8 Block 68 Unit 3"))
df %>% 
+   mutate(extract = str_extract(notes, "(?i)\\b(?:lot|unit)\\W*\\d+"))
                                       notes extract
1          LOT 56, STRATA TITLE, 56/SP77100,  LOT 56
2 18/SP71866, COMMERCIAL, 17/SP71866, lot 18  lot 18
3                        unit 9; 3R/PS732002  unit 9
4       V1602 F63, Section 8 Block 68 Unit 3  Unit 3

【讨论】:

  • 成功了!非常感谢!
【解决方案2】:

使用regmatches 的基本 R 选项

transform(
  df,
  extract = unlist(regmatches(notes, gregexpr("\\b(lot|unit)\\s\\d+", notes, ignore.case = TRUE)))
)

给予

  id                                      notes extract
1  1           LOT 56, STRATA TITLE, 56/SP77100  LOT 56
2  2 18/SP71866, COMMERCIAL, 17/SP71866, lot 18  lot 18
3  3                        unit 9; 3R/PS732002  unit 9
4  4       V1602 F63, Section 8 Block 68 Unit 3  Unit 3

数据

> dput(df)
structure(list(id = 1:4, notes = c("LOT 56, STRATA TITLE, 56/SP77100", 
"18/SP71866, COMMERCIAL, 17/SP71866, lot 18", "unit 9; 3R/PS732002",
"V1602 F63, Section 8 Block 68 Unit 3")), class = "data.frame", row.names = c(NA,
-4L))

【讨论】:

    猜你喜欢
    • 2019-10-14
    • 2021-05-05
    • 1970-01-01
    • 2019-04-28
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多