knitr::opts_chunk$set(comment = "#>", collapse = T)
library(stringr)

API changes

This release includes a change to the API: str_match_all() now returns NA if an optional group doesn’t match (previously it returned “”). This is more consistent with str_match() and other match failures.

x <- c("a=1,b=2", "c=3", "d=")

x %>% str_match("(.)=(\\d)?")
#>      [,1]  [,2] [,3]
#> [1,] "a=1" "a"  "1" 
#> [2,] "c=3" "c"  "3" 
#> [3,] "d="  "d"  NA
x %>% str_match_all("(.)=(\\d)?,?")
#> [[1]]
#>      [,1]   [,2] [,3]
#> [1,] "a=1," "a"  "1" 
#> [2,] "b=2"  "b"  "2" 
#> 
#> [[2]]
#>      [,1]  [,2] [,3]
#> [1,] "c=3" "c"  "3" 
#> 
#> [[3]]
#>      [,1] [,2] [,3]
#> [1,] "d=" "d"  NA

New features

There are three new featuers:

  • In str_replace(), replacement can now be a function that is called once for each match and who’s return value is used to replace the match.

    redact <- function(x) str_dup("-", str_length(x))
    
    x <- c("It cost $500", "We spent $1,200 on stickers")
    x %>% str_replace_all("\\$[0-9,]+", redact)
    #> [1] "It cost ----"                "We spent ------ on stickers"
  • New str_which() mimics grep():

    fruit <- c("apple", "banana", "pear", "pinapple")
    
    # Matching positions    
    str_which(fruit, "p")
    #> [1] 1 3 4
    
    # Matching values
    str_subset(fruit, "p")
    #> [1] "apple"    "pear"     "pinapple"
  • A new vignette (vignette("regular-expressions")) describes the details of the regular expressions supported by stringr. The main vignette (vignette("stringr")) has been updated to give a high-level overview of the package.

Minor improvements and bug fixes

There were three other minor improvements and bug fixes:

  • str_order() and str_sort() gain explicit numeric argument for sorting mixed numbers and strings.

  • str_replace_all() now throws an error if replacement is not a character vector. If replacement is NA_character_ it replaces the complete string with NA.

  • All functions that take a locale (e.g. str_to_lower() and str_sort()) default to “en” (English) to ensure that the default is consistent across platforms.