我想创建一个单一的正则表达式(如果可能的话)来搜索字符串并确定两个单词是否出现在同一个字符串中.我知道我可以使用两个grepl语句(如下所示),但我想使用单个正则表达式来测试这种情况.正则表达式越有效越好.
我想找到包含“man”和“dog”不区分大小写的字符串.
x <- c( "The dog and the man play in the park.","The man plays with the dog.","That is the man's hat.","Man I love that dog!","I'm dog tired" ) ## this works but I want a single regex grepl("dog",x,ignore.case=TRUE) & grepl("man",ignore.case=TRUE)
解决方法
使用正则表达式交替运算符|.
grepl(".*(dog.*man|man.*dog).*",ignore.case=TRUE)
必要时使用单词边界..
grepl(".*(\\bdog\\b.*\\bman\\b|\\bman\\b.*\\bdog\\b).*",ignore.case=TRUE)
无需领先和尾随.*
grepl("(dog.*man|man.*dog)",ignore.case=TRUE)
您可以在正则表达式本身中提供不区分大小写的修饰符.
grepl("(?i)(dog.*man|man.*dog)",x)