我想搜索一組字符串中的特定模式。R - 使用grep查找字符串中的有序模式
給出一個字符串的這兩個載體:
actions <- c("taking","using")
nouns <- c("medication","prescription")
我想找到的行動 + 名詞任意組合,在這個特定的順序,而不是名詞+行動。例如,使用下面的文字我要檢測的組合:使用藥物
- 使用prescritpion
使用下面的文字服藥
phrases <- c("he was using medication",
"medication using it",
"finding medication",
"taking the left",
"using prescription medication",
"taking medication drug")
我嘗試過使用grep("\\b(taking|using+medication|prescriptio)\\b",phrases,value = FALSE)
,但它顯然是錯誤的。
「+」是一個量詞,意思是查找前一個標記1次或更多次。你需要在它前面插入一個通配符標記'',這樣這些單詞之間的空間可以增大或縮小:'grep(「服用| +藥物|處方」,短語)' – alistaire
嘗試'grep(paste0(「 (「,paste(actions,collapse =」|「),」)\\ s +(「,paste(名詞,collapse =」|「),」)「),短語,值= FALSE),見http:/ /ideone.com/e7Ae5S –
還不夠,我不希望第四句話是一個匹配,因爲只有*動作*而不是*名詞*。 –