r gsub - replace only first match of a word

Viewed 8886

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"?

4 Answers

Please use sub instead of gsub.

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

Use a lookbehind

s <- c("21st-August-2017")
gsub("(?<=\\d)st", "xx", s, perl = TRUE)
# [1] "21xx-August-2017"

Lookarounds ascertain a specific position, in your case that a digit comes before st.
See a demo on regex101.com.

You can also specify a more specific regex. For your case

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

would work (replace all occurrences of "st" preceded by one or two numbers)

If you need to do a lot of string manipulation also look into the stringr package which has more verbose function names and a imho more sensible ordering of function paramters:

stringi::stri_replace_first_regex("21st-August-2017", "st{1}", "xx") stringi::stri_replace_first_fixed("21st-August-2017", "st", "xx")

Try sub. The two *sub functions differ only in that sub replaces only the first occurrence of a pattern whereas gsub replaces all occurrences.

Related