2016-11-12 68 views
1

我想搜索一組字符串中的特定模式。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),但它顯然是錯誤的。

  • +0

    「+」是一個量詞,意思是查找前一個標記1次或更多次。你需要在它前面插入一個通配符標記'',這樣這些單詞之間的空間可以增大或縮小:'grep(「服用| +藥物|處方」,短語)' – alistaire

    +1

    嘗試'grep(paste0(「 (「,paste(actions,collapse =」|「),」)\\ s +(「,paste(名詞,collapse =」|「),」)「),短語,值= FALSE),見http:/ /ideone.com/e7Ae5S –

    +0

    還不夠,我不希望第四句話是一個匹配,因爲只有*動作*而不是*名詞*。 –

    回答

    1

    您可以使用您的actionsnouns價值觀建設的交替組,並把它們放入一個更大的正則表達式:

    actions <- c("taking","using") 
    nouns <- c("medication","prescription") 
    phrases <- c("he was using medication","medication using it","finding medication","taking the left","using prescription medication","taking medication drug") 
    grep(paste0("(",paste(actions, collapse="|"), ")\\s+(", paste(nouns,collapse="|"),")"), phrases, value=FALSE) 
    ## => [1] 1 5 6 
    ## and a visual check 
    grep(paste0("(",paste(actions, collapse="|"), ")\\s+(", paste(nouns,collapse="|"),")"), phrases, value=TRUE) 
    ## => [1] "he was using medication" "using prescription medication" "taking medication drug" 
    

    online R demo

    產生的正則表達式看起來像

    (taking|using)\s+(medication|prescription) 
    

    請參閱regex demo

    詳細

    • (taking|using) - 交替組匹配任一taking或(|using
    • \s+ - 1以上空格
    • (medication|prescription) - 交替組匹配任一medicationprescription

    注意(...)捕獲團可以用(?:...)非捕獲那些,以避免保持子匹配在存儲器中替換。

    +1

    感謝這正是我正在尋找的。我會檢查演示! –