Skip to content

Commit

Permalink
Vectorise fix_replacement
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Aug 17, 2016
1 parent 918fec2 commit 4ac3be1
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
6 changes: 5 additions & 1 deletion R/replace.r
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ str_replace <- function(string, pattern, replacement) {
#' @rdname str_replace
str_replace_all <- function(string, pattern, replacement) {
if (!is.null(names(pattern))) {
vec <- FALSE
replacement <- unname(pattern)
pattern <- names(pattern)
vec <- FALSE
} else {
vec <- TRUE
}
Expand All @@ -75,6 +75,10 @@ str_replace_all <- function(string, pattern, replacement) {
}

fix_replacement <- function(x) {
vapply(x, fix_replacement_one, character(1), USE.NAMES = FALSE)
}

fix_replacement_one <- function(x) {
escape_dollar <- function(x) if (x == "$") "\\$" else x

chars <- str_split(x, "")[[1]]
Expand Down
5 changes: 5 additions & 0 deletions tests/testthat/test-replace.r
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ test_that("replacement strings with capture groups refs and dollar signs work",
expect_equal(str_replace("aba", "(b)", "\\\\1$\\1$\\\\1"), "a\\1$b$\\1a")
})

test_that("can replace multiple matches", {
x <- c("a1", "b2")
y <- str_replace_all(x, c("a" = "1", "b" = "2"))
expect_equal(y, c("11", "22"))
})

# fix_replacement ---------------------------------------------------------

Expand Down

0 comments on commit 4ac3be1

Please sign in to comment.