Home > front end >  Extract position of " " and "*" symbol in string using R
Extract position of " " and "*" symbol in string using R

Time:12-28

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!

CodePudding user response:

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

CodePudding user response:

Some other base R workarounds

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

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