我想创建一个单一的正则表达式(如果可能的话)来搜索字符串并确定两个单词是否出现在同一个字符串中.我知道我可以使用两个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", x, ignore.case=TRUE)
Run Code Online (Sandbox Code Playgroud)
Avi*_*Raj 11
使用正则表达式交替运算符|.
grepl(".*(dog.*man|man.*dog).*", x, ignore.case=TRUE)
Run Code Online (Sandbox Code Playgroud)
必要时使用单词边界..
grepl(".*(\\bdog\\b.*\\bman\\b|\\bman\\b.*\\bdog\\b).*", x, ignore.case=TRUE)
Run Code Online (Sandbox Code Playgroud)
无需领先和尾随 .*
grepl("(dog.*man|man.*dog)", x, ignore.case=TRUE)
Run Code Online (Sandbox Code Playgroud)
您可以在正则表达式本身中提供不区分大小写的修饰符.
grepl("(?i)(dog.*man|man.*dog)", x)
Run Code Online (Sandbox Code Playgroud)
您可以使用类似 Perl 的正则表达式和 2 个前瞻:
grepl("^(?=.*\\bman\\b)(?=.*\\bdog\\b)", x, ignore.case=TRUE, perl=TRUE)
Run Code Online (Sandbox Code Playgroud)
上述输入的结果:[1] TRUE TRUE FALSE TRUE FALSE
前瞻^(?=.*\\bman\\b)(?=.*\\bdog\\b)仅检查整个单词man和dog输入,并且仅在两者都存在时才通过,无论它们的顺序如何(dog可能在之前)man,反之亦然)。
由于^字符串起始锚点,这些检查仅针对每个输入执行一次,从而将性能保持在良好的水平。