Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r gsub - replace only first match of a word [duplicate]

Tags:

regex

r

gsub

I have a string like this: "21st-August-2017" and I would like to replace the "st" after 21 with "xx" so that the result is

"25xx-August-2017"

I have tried using regex repetition quantifiers, e.g.

gsub("st{1}", "xx", "21st-August-2017")

But this still replaces both instances of "st". How can I specify that it should match only the first instance of "st"?

like image 227
Slug Pue Avatar asked Dec 06 '22 13:12

Slug Pue


1 Answers

Please use sub instead of gsub.

Replace the first occurrence of a pattern with sub or replace all occurrences with gsub.

like image 158
Daniel Avatar answered Dec 22 '22 10:12

Daniel