【问题标题】:match strings exactly on lookup table in R [duplicate]在R中的查找表上完全匹配字符串[重复]
【发布时间】:2020-09-04 14:12:19
【问题描述】:

我有一个查找值表,其中包含要查找和替换的模式,但这些模式有相互包含的字符串,我想完全匹配它们。

lookup <- tibble(
  pattern = c("ONE", "ONET", "ONETR"),
  replacement = c("one new", "this is 2", "for 3")
)
other_table <- tibble(
  strings = c(
    "I want to replace ONE",
    "Or ONET is what to change",
    "We can change ONE again",
    "ONETR also can be replaced"
  ),
  other_dat = 1:4
)

我尝试过使用stringi,但是当模式相互包含时,这不起作用。

other_table %>%
  mutate(
    strings = stringi::stri_replace_all_fixed(
      strings, 
      pattern = lookup$pattern, 
      replacement = lookup$replacement,
      vectorize_all = FALSE)
    )

我可以使用什么函数将in_table$strings 中的所有模式替换为lookup$replacement

期望的输出:

  strings                        other_dat
  <chr>                              <int>
1 I want to replace one new              1
2 Or this is 2 is what to change         2
3 We can change one new again            3
4 for 3 also can be replaced             4

任何帮助表示赞赏!

【问题讨论】:

    标签: r regex stringr stringi


    【解决方案1】:

    在您的正则表达式中使用单词边界(不固定),例如,"\\b"

    other_table %>%
      mutate(
        strings = stringi::stri_replace_all(
          strings, 
          regex = paste0("\\b", lookup$pattern, "\\b"), 
          replacement = lookup$replacement,
          vectorize_all = FALSE)
        )
    # # A tibble: 4 x 2
    #   strings                        other_dat
    #   <chr>                              <int>
    # 1 I want to replace one new              1
    # 2 Or this is 2 is what to change         2
    # 3 We can change one new again            3
    # 4 for 3 also can be replaced             4
    

    【讨论】:

      猜你喜欢
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多