Use grep to find letter without separate

独自空忆成欢 提交于 2020-01-17 06:09:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!