Trim Characters from the Left and/or Right Side of a String

Share:

Description

These functions may be used e.g. to get rid of unnecessary whitespaces from strings. Trimming ends at the first or starts at the last pattern match.

Usage

1
2
3
4
5
6
7
stri_trim_both(str, pattern = "^WHITE_SPACE")

stri_trim_left(str, pattern = "^WHITE_SPACE")

stri_trim_right(str, pattern = "^WHITE_SPACE")

stri_trim(str, side = c("both", "left", "right"), pattern = "^WHITE_SPACE")

Arguments

str

character vector

pattern

character vector with character class identifiers that should be preserved, see stringi-search-charclass, defaults '^WHITE_SPACE'

side

character [stri_trim only]; defaults to "both"

Details

Vectorized over str and pattern.

stri_trim is a convenience function, which dispatches control to stri_trim_*. Unless you are very lazy, do not use it: it is slower.

Contrary to many other string processing libraries, our trimming functions are quite general. A character class, given by pattern, may be adjusted to suit your needs (most often you will use the default value or a negation of some character class, i.e. with ^ at the beginning).

With these functions you may very quickly extract data, which in some cases require using regular expressions. E.g. you may get "23.5" out of "total of 23.5 bitcoins".

For trimming whitespaces, please note the difference between Unicode binary property 'WHITE_SPACE' (more general) and general character category 'Z', see stringi-search-charclass

Value

All these functions return a character vector.

See Also

Other search_charclass: stri_count_charclass; stri_detect_charclass; stri_extract_all_charclass, stri_extract_all_charclass, stri_extract_first_charclass, stri_extract_first_charclass, stri_extract_last_charclass, stri_extract_last_charclass; stri_locate_all_charclass, stri_locate_all_charclass, stri_locate_first_charclass, stri_locate_first_charclass, stri_locate_last_charclass, stri_locate_last_charclass; stri_replace_all_charclass, stri_replace_all_charclass, stri_replace_first_charclass, stri_replace_first_charclass, stri_replace_last_charclass, stri_replace_last_charclass; stri_split_charclass, stri_split_charclass; stringi-search-charclass; stringi-search

Examples

1
2
3
4
stri_trim_left("               aaa")
stri_trim_right("rexamine.com/", "^P")
stri_trim_both(" Total of 23.5 bitcoins. ", "N")
stri_trim_both(" Total of 23.5 bitcoins. ", "L")

Want to suggest features or report bugs for rdrr.io? Use the GitHub issue tracker.