How do I include the wildcard in a returned expression with gsub in R?

Viewed 41

I have a string in R:

mystring <- "2 and 4"

I want to use gsub to put " hours" after every occurance of a number, so that the string looks like this:

"2 hours and 4 hours"

I have tried this, which matches the number, but I want the number returned in the output:

gsub("\\d{1}", "\\d{1} hours", mystring)
[1] "d{1} hours and d{1} hours"

How do I include the original number in the output?

3 Answers

We capture the digit (\\d) before the word boundary (\\b) as a group and in the replacement, specify the backreference (\\1) of the captured group followed by space and then the substring 'hours'

gsub("(\\d)\\b", "\\1 hours", mystring)
[1] "2 hours and 4 hours"

With stringr, we can use an R function on the match to construct the replacement:

library(stringr)
str_replace_all(
  mystring,
  "\\d",
  \(x) paste(x, "hours")
)
# [1] "2 hours and 4 hours"

You can use a non consuming look behind:

gsub("(?<=\\d)", " hours", mystring, perl=TRUE)
#[1] "2 hours and 4 hours"

In case there are more digits use a boundary in addition:

gsub("(?<=\\d)\\b", " hours", mystring, perl=TRUE)
#[1] "2 hours and 4 hours"
Related