Extract position of "+" and "*" symbol in string using R

Viewed 67

I am looking for a manner to extract the position of "*" and "+" symbols in R string.

test <- "x+y"
unlist(gregexpr("+", test))
[1] 1 2 3
unlist(gregexpr("y", test))
[1] 3

It returns the position of x or y but returns all positions for + or *.

Thank you!

2 Answers

Use fixed = TRUE, by default it is FALSE and uses the regex mode where + is a metacharacter. According to ?regex

+ - The preceding item will be matched one or more times.

* - The preceding item will be matched zero or more times.

unlist(gregexpr("+", test, fixed = TRUE))
[1] 2

Some other base R workarounds

> which(unlist(strsplit(test, "")) == "+")
[1] 2

> which(utf8ToInt(test) == utf8ToInt("+"))
[1] 2
Related