2

I want to get all the positions of "_" in my string:

MyString <- "Test_Test_Test"

grep("_", MyString)

This returns however:

[1] 1

What am I doing wrong?

s_baldur
  • 29,441
  • 4
  • 36
  • 69
MichiZH
  • 5,587
  • 12
  • 41
  • 81

2 Answers2

3

Use gregexpr rather than grep

 MyString<-"Test_Test_Test"
> gregexpr('_', MyString)
[[1]]
[1]  5 10
attr(,"match.length")
[1] 1 1
attr(,"useBytes")
[1] TRUE
jdharrison
  • 30,085
  • 4
  • 77
  • 89
0

I'd recommend Hadley's stringr package:

library("stringr")

MyString <- "Test_Test_Test"
str_locate_all(MyString, "_")
# [[1]]
#  start end
# [1,]     5   5
# [2,]    10  10
blmoore
  • 1,487
  • 16
  • 31