2017-07-26 62 views
1

我想用regex匹配一些字符串,同時否定R中的其他字符串。在下面的例子中,我想排除我想要匹配的字符串子部分。下面的示例使用Regular expression to match a line that doesn't contain a word?的答案。在匹配其他字符時取反字符串

我的困惑是,當我嘗試這一點,grepl拋出一個錯誤:

錯誤grepl(mypattern,MyString的): 無效的正則表達式「桌面遊戲|(^((?!遊戲))* $。 )」,原因 '無效的正則表達式'

mypattern <- "boardgames|(^((?!games).)*$)" 
mystring <- c("boardgames", "boardgames", "games") 

grepl(mypattern, mystring) 

注意事項使用期望的結果(即T,T,F)str_detect返回運行,但我想用grepl。

回答

2

我們需要perl = TRUE作爲默認選項是perl = FALSE

grepl(mypattern, mystring, perl = TRUE) 
#[1] TRUE TRUE FALSE 

Perl-compatible regexps使用

根據?regexp

The perl = TRUE argument to grep, regexpr, gregexpr, sub, gsub and strsplit switches to the PCRE library that implements regular expression pattern matching using the same syntax and semantics as Perl 5.x, with just a few differences.

這是必要的