问题
I have these codes:
x=c('a','a,b','a-c','ab')
y=c('a')
grep(y,x,ignore.case = T)
The result is
> grep(y,x)
[1] 1 2 3 4
But I expect that the result should be "1 2 3", once "a" is separated by anything or just "a", except "a" is not separated like "ab". Thank you!
回答1:
Add a word boundary to y
:
x=c('a','a,b','a-c','ab')
y=c('a\\b')
grep(y,x,ignore.case = T)
# [1] 1 2 3
回答2:
As the OP's wants to have a pattern that involves not having any letters following 'a' ([^a-z]
) or (|
) it can be the end of the string $
.
grep("a([^a-z]|$)", x)
#[1] 1 2 3
Or if we want to be specific that either punctuation ([[:punct:]]
) follows 'a' or (|
) it is the end of string, then
grep("a([[:punct:]]|$)", x)
#[1] 1 2 3
来源:https://stackoverflow.com/questions/38358926/use-grep-to-find-letter-without-separate