Skip to contents

Replace or remove non-alphanumeric characters, keeping dots and handling underscores as indicated by keep_underscores.

Usage

replace_nonalnum(x, replacement = "_", keep_underscore = TRUE)

Arguments

x

character vector with the (possibly empty) strings to remove non-alphanumeric characters from.

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

TRUE or FALSE: keep underscores? If FALSE, underscores are replaced by replacement, which only makes sense if a non-default replacement is used such that it is not an underscore, see the last Example.

Value

x with non-alphanumeric characters other than dots, and possibly underscores, replaced by replacement.

Details

This implementation uses the character class [:alnum:] that depends on the current locale, see the Programming notes in checkinput::all_names().

Empty strings are allowed as input to x because they might also be returned by replace_nonalnum() if the empty character string ("") is used for replacement.

See also

trimws() to remove leading and/or trailing whitespace; replace_vals() to replace specific values; checkinput::all_names() and checkinput::is_path() for more specific checks.

Other functions to check equality: are_equal(), check_case(), get_file_path(), not_in(), replace_vals(), signif_custom()

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"