2
x <- c("This is a sentence about axis",
     "A second pattern is also listed here")

sub(".*is", "XY", x)
#[1] "XY"         "XYted here"

gsub(".*is", "XY", x)
#[1] "XY"         "XYted here"
Ronak Shah
  • 286,338
  • 16
  • 97
  • 143
andrew
  • 31
  • 3

1 Answers1

3

When you are using the pattern ".*is", it matches everything from start of the string to the last "is", which in first sentence is "is" in "axis" and "is" in "listed" in 2nd string. Hence, everything upto that part gets replaced by "XY".

What probably you might be expecting is :

sub("is", "XY", x)
#[1] "ThXY is a sentence about axis"        "A second pattern XY also listed here"

gsub("is", "XY", x)
#[1] "ThXY XY a sentence about axXY"        "A second pattern XY also lXYted here

As you can see in the sub call only the first "is" is replaced whereas in gsub all of the instances of "is" are replaced with "XY".

Ronak Shah
  • 286,338
  • 16
  • 97
  • 143