regex match substring unless another substring matches

前端 未结 2 1999
忘掉有多难
忘掉有多难 2021-01-18 23:19

I\'m trying to dig deeper into regexes and want to match a condition unless some substring is also found in the same string. I know I can use two grepl statem

2条回答
  •  清酒与你
    2021-01-18 23:49

    You can use the anchored look-ahead solution (requiring Perl-style regexp):

    grepl("^(?!.*park)(?=.*dog.*man|.*man.*dog)", x, ignore.case=TRUE, perl=T)
    

    Here is an IDEONE demo

    • ^ - anchors the pattern at the start of the string
    • (?!.*park) - fail the match if park is present
    • (?=.*dog.*man|.*man.*dog) - fail the match if man and dog are absent.

    Another version (more scalable) with 3 look-aheads:

    ^(?!.*park)(?=.*dog)(?=.*man)
    

提交回复
热议问题