Replace or remove non-alphanumeric characters, keeping dots and handling
underscores as indicated by keep_underscores.
Arguments
- x
character vector with strings to remove non-alphanumeric characters from. Empty strings (
"") are allowed.- replacement
character string used to replace non-alphanumeric characters. It might be empty (i.e.,
"") to remove instead of replace non-alphanumeric characters.- keep_underscore
TRUEorFALSE: keep underscores? IfFALSE, underscores are replaced byreplacement, which is only apparent if a non-defaultreplacementis used such that it is not an underscore, see the last 'Example'.
Value
x with non-alphanumeric characters other than dots, as well as underscores
if keep_underscores is FALSE, replaced by replacement. An empty string
("") is returned if the empty character string ("") is used for
replacement and x does not contain non-replaced characters.
Details
This implementation uses the character class [:alnum:] that
depends on the current locale, see the 'Programming Notes' in
checkinput::all_names().
See also
trimws() to remove leading whitespace, trailing whitespace, or both;
replace_vals(), with more relevant links, to replace specific values;
checkinput::all_names() and checkinput::is_path() for checks on the
validity of strings.
Other functions to check equality:
are_equal(),
check_case(),
get_file_path(),
not_in(),
replace_vals(),
signif_custom()
Other functions to modify character vectors:
as.numeric_safe(),
reexports,
replace_vals(),
signal_text(),
unpaste_unquote(),
vect_to_char(),
wrap_text()
Examples
replace_nonalnum("a+b.txt")
#> [1] "a_b.txt"
replace_nonalnum("a b.txt")
#> [1] "a_b.txt"
replace_nonalnum("ab12._") # returned unchanged
#> [1] "ab12._"
replace_nonalnum(c("a+b.txt", "a b.txt", "ab12._"))
#> [1] "a_b.txt" "a_b.txt" "ab12._"
# Removing instead of replacing nonalphanumeric characters
replace_nonalnum("a+b.txt", replacement = "") # "ab.txt"
#> [1] "ab.txt"
# Handling underscores
replace_nonalnum("a+bc_d.txt", replacement = "",
keep_underscore = TRUE) # "abc_d.txt"
#> [1] "abc_d.txt"
replace_nonalnum("a+bc_d.txt", replacement = "",
keep_underscore = FALSE) # "abcd.txt"
#> [1] "abcd.txt"
# Seems to keep the underscore because the
# default 'replacement' is an underscore
replace_nonalnum("a+bc_d.txt",
keep_underscore = FALSE) # "a_bc_d.txt"
#> [1] "a_bc_d.txt"