我想深入挖掘正则表达式,并希望匹配条件,除非在同一个字符串中也找到一些子字符串。我知道我可以使用两个grepl
语句(如下所示),但我希望使用单个正则表达式来测试这种情况,因为我正在推动我的理解。假设我想使用"(dog.*man|man.*dog)"
(taken from here)匹配单词“狗”和“男人”,但如果字符串包含子字符串“park”,则不会。我想我可以使用(*SKIP)(*FAIL)
来否定“park”,但这不会导致字符串失败(如下所示)。正则表达式匹配子字符串,除非另一个子字符串匹配
- 我如何才能找到“狗” &“人”与1个正则表达式的逻辑,但不是“公园”相匹配?
- 我对
(*SKIP)(*FAIL)|
的理解有什么问题?
代码:
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",
"The dog park is no place for man.",
"Park next to this dog's man."
)
# Could do this but want one regex
grepl("(dog.*man|man.*dog)", x, ignore.case=TRUE) & !grepl("park", x, ignore.case=TRUE)
# Thought this would work, it does not
grepl("park(*SKIP)(*FAIL)|(dog.*man|man.*dog)", x, ignore.case=TRUE, perl=TRUE)
尼斯我在想你因为某些原因不能使用lokaround内的量词。 –
您可以在预测中使用量词,但不能在PCRE后面使用量词。一个量词可以用在,NET后顾之外,并且只有具有最小值和最大值的限制量词可用于Java的约束宽度Java后代。 –