0

I have a vector which have following three strings

test <- c("www.example.com/topic/university-admission",
          "www.example.com/topic/school-admission",
          "www.example.com/college-admission")

I want to extract all the element which have pattern like this "www.example.com/topic/"

One way is just looking at vector and extract as per the index location of that element. But this will be challenging if vector has length of say 100.

Is there any way to do this using string pattern matching?

denis
  • 5,580
  • 1
  • 13
  • 40
djMohit
  • 151
  • 1
  • 10
  • 3
    `grep("^www.example.com/topic/", test, value = T)` – Sonny May 29 '19 at 10:08
  • what to do for this case [1] www.example.com/topic/university-admission [2] www.example.com/topic/university-admission/college [3] www.example.com/topic/school-admission [4] www.example.com/topic/school-admission/college now i want only [1] www.example.com/topic/university-admission [2] www.example.com/topic/school-admission – djMohit May 29 '19 at 10:14
  • ^ means that it will look if the string starts with the given characters. – Sonny May 29 '19 at 10:17

1 Answers1

1
test[startsWith(x = test, "www.example.com/topic/")]
# [1] "www.example.com/topic/university-admission" "www.example.com/topic/school-admission"  
s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • Thanks its working.....What to do if i have to match "www.example.com/topic/university-admission/college" Inplace of "university-admission" any string can come....thanks once again – djMohit May 29 '19 at 12:00
  • try: `test[startsWith(x = test, "www.example.com/[^/]/college")]` – s_baldur May 29 '19 at 12:15