Я пытаюсь удалить все появления строки «J». из более длинной строки, но только там, где J. не находится в круглых скобках:
Начинать:
text = "This is J. one instance and J. another (this one should stay J.) but this one should go J. (and stay J.) (and stay J. and stay J.) and go J."
Конец с:
"This is one instance and another (this one should stay J.) but this one should go (and stay J.) (and stay J. and stay J.) and go"
Мне удалось добиться этого с помощью этой комбинации gsub:
gsub("\\)[^(]+J.", ")", gsub("^[^(]+J.", "", text))
[1] " another (this one should stay J.) (and stay J.) (and stay J. and stay J.)"
Но в идеале я мог бы оставить текст за пределами (), кроме J.s
Использование dplyr
, приведение к tibble
и группировка по (
и )
library(dplyr) # < dplyr 1.1.0 use summarize instead reframe
tibble(t = unlist(strsplit(text, " "))) %>%
mutate(beg = grepl("\\(", t), end = grepl("\\)", lag(t))) %>%
group_by(grp = cumsum(beg|end)) %>%
mutate(is = !grepl("\\(", t[1])) %>%
reframe(text = if_else(is, sub("J\\.", "", t), t)) %>%
filter(text != "") %>%
select(-grp) %>%
unlist() %>%
paste(collapse = " ")
[1] "This is one instance and another (this one should stay J.) but this one should go (and stay J.) (and stay J. and stay J.) and go"
В base R
мы могли бы использовать *SKIP
, *FAIL
, чтобы пропустить совпадения в скобках.
gsub("(\\([^\\)]*J\\.)(*SKIP)(*FAIL)|\\s*J\\.", "", text, perl = TRUE)
-выход
[1] "This is one instance and another (this one should stay J.) but this one should go (and stay J.) (and stay J. and stay J.) and go"