Get indices of all character elements matches in string in R

 ̄綄美尐妖づ 提交于 2019-12-25 01:43:45

问题


I want to get indices of all occurences of character elements in some word. Assume these character elements I look for are: l, e, a, z.

I tried the following regex in grep function and tens of its modifications, but I keep receiving not what I want.

grep("/([leazoscnz]{1})/", "ylaf", value = F)

gives me

numeric(0)

where I would like:

[1] 2 3 

回答1:


To use grep work with individual characters of a string, you first need to split the string into separate character vectors. You can use strsplit for this:

strsplit("ylaf", split="")[[1]]
[1] "y" "l" "a" "f"

Next you need to simplify your regular expression, and try the grep again:

strsplit("ylaf", split="")[[1]]
grep("[leazoscnz]", strsplit("ylaf", split="")[[1]])

[1] 2 3

But it is easier to use gregexpr:

gregexpr("[leazoscnz]", "ylaf")
[[1]]
[1] 2 3
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE


来源:https://stackoverflow.com/questions/24508413/get-indices-of-all-character-elements-matches-in-string-in-r

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