Скажем, у меня есть строка -
some_string <- "this is a string with some numbers 9639998 21057535 1000 2021 2022"
Я хотел бы удалить числовые шаблоны длиной 7 символов, длиной 8 символов и длиной 4 символа, ЗА ИСКЛЮЧЕНИЕМ, если это 1000. По сути, я хочу получить следующий результат:
"this is a string with some numbers 1000"
Используйте gsub
здесь с шаблоном регулярного выражения \b(?:\d{7,8}|(?!1000\b)\d{4})\b
:
some_string <- "this is a string with some numbers 9639998 21057535 1000 2021 2022"
output <- gsub("\\b(?:\\d{7,8}|(?!1000\\b)\\d{4})\\b", "", some_string, perl=TRUE)
output
[1] "this is a string with some numbers 1000 "
На самом деле, лучшая версия, которая убирает свободные пробелы, была бы такой:
some_string <- "this is a string with some numbers 9639998 21057535 1000 2021 2022"
output <- gsub("\\s*(?:\\d{7,8}|(?!1000\\b)\\d{4})\\s*", " ", some_string, perl=TRUE)
output <- gsub("^\\s+|\\s+$", "", gsub("\\s{2,}", " ", output))
output
[1] "this is a string with some numbers 1000"
Опция stringr для сохранения 1000 и длин, отличных от 4,7 и 8. (В выборку данных включена длина 5.)
library(stringr)
"this is a string with some numbers 9639998 21057535 1000 2021 20022 2022" |>
str_remove_all("(?!1000)\\b(\\d{7,8}|\\d{4})\\b") |>
str_squish()
#> [1] "this is a string with some numbers 1000 20022"
Created on 2022-05-17 by the reprex package (v2.0.1)
Apols тоже зациклен на результате. Обновлено, чтобы сохранить длину 5.