Detect or remove the longest common prefix (LCP) or longest common suffix (LCS) across a character vector.
Usage
str_get_lcp(x, ignore_case = FALSE, word = "[[:alnum:]]+")
str_get_lcs(x, ignore_case = FALSE, word = "[[:alnum:]]+")
str_remove_lcp(x, ignore_case = FALSE, word = "[[:alnum:]]+")
str_remove_lcs(x, ignore_case = FALSE, word = "[[:alnum:]]+")Arguments
- x
A character vector. Non-character inputs are coerced with
as.character().- ignore_case
Logical. If
TRUE, case is ignored when detecting the common prefix or suffix.- word
Character regex defining what counts as a word when trimming the detected common prefix or suffix. When set, the functions back up only if the raw cut would fall inside a word, while preserving separators that are already outside the word. Use
NULLto disable word checking and return or remove the raw common prefix or suffix. Default is"[[:alnum:]]+".
Value
str_get_lcp() and str_get_lcs() return a length-1 character vector.
str_remove_lcp() and str_remove_lcs() return a character vector of the
same length as x.
Details
When ignore_case = TRUE, matching is performed on an upper-cased copy of
the input, while returned values preserve the original casing of the first
element. If x contains NA, the functions warn and behave as if no common
prefix or suffix were found.
Examples
x1 <- c("prefix_alpha", "prefix_beta", "prefix_gamma")
str_get_lcp(x1)
#> [1] "prefix_"
str_remove_lcp(x1)
#> [1] "alpha" "beta" "gamma"
x2 <- c("alpha_suffix", "beta_suffix", "gamma_suffix")
str_get_lcs(x2)
#> [1] "_suffix"
str_remove_lcs(x2)
#> [1] "alpha" "beta" "gamma"
x3 <- c("please select - brown", "please select - blue")
str_get_lcp(x3)
#> [1] "please select - "
str_remove_lcp(x3)
#> [1] "brown" "blue"
# raw common prefix; this is not what we usually want
str_get_lcp(x3, word = NULL)
#> [1] "please select - b"