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"
Asked
Active
Viewed 256 times
3

Ronak Shah
- 377,200
- 20
- 156
- 213

andrew
- 41
- 3
-
1If you call `?sub` in R, in the description it gives **`sub` and `gsub` perform replacement of the first and all matches respectively.** – UseR10085 Feb 17 '20 at 07:43
-
Because `.*is` matches all up to the last occurrence of `is` – Wiktor Stribiżew Feb 17 '20 at 07:50
1 Answers
4
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
- 377,200
- 20
- 156
- 213