在下面的示例中,我試圖提取“最高法院”或“美國最高法院”與下一個日期(包括日期)之間的文本。下面的結果不是我想要的,因為結果 2 包括“美國的”。
我認為錯誤是由于.*?零件造成的,因為.它也可以匹配“美國的”。任何想法如何排除它?我想更一般地說,問題是如何將可選的“元素”包含在后視中(這似乎不可能,因為?它是一個非固定長度的輸入)。非常感謝!
library(tidyverse)
txt <- c("The US Supreme Court decided on 2 April 2020 The Supreme Court of the United States decided on 5 March 2011 also.")
str_extract_all(txt, regex("(?<=Supreme Court)(\\sof the United States)?.*?\\d{1,2}\\s\\w \\s\\d{2,4}"))
#> [[1]]
#> [1] " decided on 2 April 2020"
#> [2] " of the United States decided on 5 March 2011"
由reprex 包(v2.0.1)于 2021 年 12 月 9 日創建
我也試過
str_extract_all(txt, regex("(?<=(Supreme Court)|(Supreme Court of the United States)).*?\\d{1,2}\\s\\w \\s\\d{2,4}"))
然而結果是一樣的。
uj5u.com熱心網友回復:
您可以使用 str_match_all 和組捕獲來執行此操作:
str_match_all(txt, regex("Supreme Court(?:\\sof the United States)?(.*?\\d{1,2}\\s\\w \\s\\d{2,4})")) %>%
.[[1]] %>% .[, 2]
[1] " decided on 2 April 2020" " decided on 5 March 2011"
uj5u.com熱心網友回復:
在這種情況下,我更喜歡使用perl在 Base R 中實作的引擎,而不是使用 stringr/stringi 使用的 ICU 庫引擎。
pattern <- "Supreme Court (of the United States ?)?\\K.*?\\d{1,2}\\s\\w \\s\\d{2,4}"
regmatches(txt, gregexpr(pattern, txt, perl = TRUE))
[[1]]
[1] "decided on 2 April 2020" "decided on 5 March 2011"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/377497.html
