3

I'd like to remove all elements of a string after a certain keyword. Example :

this.is.an.example.string.that.I.have

Desired Output :

This.is.an.example

I've tried using gsub('string', '', list) but that only removes the word string. I've also tried using the gsub('^string', '', list) but that also doesn't seem to work.

Thank you.

eigenfoo
  • 229
  • 2
  • 9

3 Answers3

5

Following simple sub may help you here.

sub("\\.string.*","",variable)

Explanation: Method of using sub

sub(regex_to_replace_text_in_variable,new_value,variable)

Difference between sub and gsub:

sub: is being used for performing substitution on variables.

gsub: gsub is being used for same substitution tasks only but only thing it will be perform substitution on ALL matches found though sub performs it only for first match found one.

From help page of R:

sub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

gsub(pattern, replacement, x, ignore.case = FALSE, perl = FALSE, fixed = FALSE, useBytes = FALSE)

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

You can try this positive lookbehind regex

S <- 'this.is.an.example.string.that.I.have'
gsub('(?<=example).*', '', S, perl=TRUE)
# 'this.is.an.example'
CPak
  • 13,260
  • 3
  • 30
  • 48
0

You can use strsplit. Here you split your string after a key word, and retain the first part of the string.

x <- "this.is.an.example.string.that.I.have"
strsplit(x, '(?<=example)', perl=T)[[1]][1]

[1] "this.is.an.example"
milan
  • 4,782
  • 2
  • 21
  • 39