R-regex:匹配不以模式开头的字符串 [英] R-regex: match strings not beginning with a pattern
问题描述
我想使用正则表达式来查看字符串是否以某种模式开头.虽然我可以使用:[^
将某些字符列入黑名单,但我不知道如何将某个模式列入黑名单.
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 blacklist a pattern.
> grepl("^[^abc].+$", "foo")
[1] TRUE
> grepl("^[^abc].+$", "afoo")
[1] FALSE
我想做一些类似 grepl("^[^(abc)].+$", "afoo")
的事情,然后得到 TRUE
,即如果字符串不以 abc
序列开头,则匹配.
I'd like to do something like grepl("^[^(abc)].+$", "afoo")
and get TRUE
, i.e. to match if the string does not start with abc
sequence.
请注意,我知道这篇文章,我也尝试使用 perl = TRUE
,但没有成功:
Note that I'm aware of this post, and I also tried using perl = TRUE
, but with no success:
> grepl("^((?!hede).)*$", "hede", perl = TRUE)
[1] FALSE
> grepl("^((?!hede).)*$", "foohede", perl = TRUE)
[1] FALSE
有什么想法吗?
推荐答案
是的.将零宽度前瞻/外部/其他括号.这应该给你这个:
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
我认为这是你想要的.
或者,如果您想捕获整个字符串,^(?!hede)(.*)$
和 ^((?!hede).*)$
是等价的,也是可接受的.
Alternately if you want to capture the entire string, ^(?!hede)(.*)$
and ^((?!hede).*)$
are both equivalent and acceptable.
这篇关于R-regex:匹配不以模式开头的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!