-1

example:

"A.B.C.D"
"apple.good.sad.sea"
"X1.AN2.ED3.LK8"

What I need is to obtain the string specifically between the second dot and the third dot.

result:

"C"
"sad"
"ED3"

How can I do this?

recon
  • 157
  • 9

4 Answers4

2

You can use base::strsplit, loop thr the elements to get the 3rd one

v <- c("A.B.C.D", "apple.good.sad.sea", "X1.AN2.ED3.LK8")
sapply(strsplit(v, "\\."), `[[`, 3L)

output:

[1] "C"   "sad" "ED3"
chinsoon12
  • 25,005
  • 4
  • 25
  • 35
2

You can use unlist(strsplit(str,split = "."))[3] to get the third sub-string, where the original string is split by "." when you apply strsplit

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

Using regex in gsub.

v <- c("A.B.C.D", "apple.good.sad.sea", "X1.AN2.ED3.LK8", "A.B.C.D.E")
gsub("(.*?\\.){2}(.*?)(\\..*)", "\\2", v)
# [1] "C"   "sad" "ED3" "C"  
jay.sf
  • 60,139
  • 8
  • 53
  • 110
2

I'd use

sub("^([^.]*\\.){2}([^.]*)\\..*", "\\2", x)
# [1] "C"   "sad" "ED3"
talat
  • 68,970
  • 21
  • 126
  • 157