R-regex: match strings not beginning with a pattern

后端 未结 3 533
谎友^
谎友^ 2020-12-29 06:43

I\'d like to use regex to see if a string does not begin with a certain pattern. While I can use: [^ to blacklist certain characters, I can\'t figure out how to

3条回答
  •  感动是毒
    2020-12-29 07:03

    Yeah. Put the zero width lookahead /outside/ the other parens. That should give you this:

    > grepl("^(?!hede).*$", "hede", perl = TRUE)
    [1] FALSE
    > grepl("^(?!hede).*$", "foohede", perl = TRUE)
    [1] TRUE
    

    which I think is what you want.

    Alternately if you want to capture the entire string, ^(?!hede)(.*)$ and ^((?!hede).*)$ are both equivalent and acceptable.

提交回复
热议问题