我正在努力解決以下問題的正則運算式:比如說,我有一系列字串,它們都包含多次出現的關鍵字Appendix或appendix像這樣:
text <- c("Appendix abc Appendix def appendix final",
"blah blah Appendix abc Appendix finalissimo")
我想洗掉最后一次出現“附錄”之后的所有內容,包括關鍵字本身以獲得以下所需的輸出:
1 Appendix abc Appendix def
2 blah blah Appendix abc
我知道(a)tidyverse解決方案是可能的(例如,在特定單詞的最后一次出現之前提取所有文本,但在這里我對正則運算式解決方案特別感興趣。我嘗試了許多這樣的正則運算式解決方案但似乎沒有一個作業。我認為最有希望的是這涉及負前瞻和反向參考,但它也不會產生預期的結果:
library(stringr)
str_extract(text, "(?i).*(?!(appendix).*\\1)")
我將不勝感激為什么這個解決方案不起作用的建議以及一個起作用的正則運算式解決方案。
uj5u.com熱心網友回復:
我會在這里使用帶有前瞻邏輯的正則運算式:
text <- c("Appendix abc Appendix def appendix final",
"blah blah Appendix abc Appendix finalissimo")
output <- sub("(?i)\\s appendix(?!.*\\bappendix\\b).*", "", text, perl=TRUE)
output
[1] "Appendix abc Appendix def" "blah blah Appendix abc"
uj5u.com熱心網友回復:
您可以使用sub. 第一個.*是貪婪的,會拿走所有東西,直到最后一場比賽Appendix.*。
sub("(.*)Appendix.*", "\\1", text, TRUE)
#[1] "Appendix abc Appendix def " "blah blah Appendix abc "
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480416.html
上一篇:按條件應用strsplit
