@@ -49,3 +49,58 @@ str_detect <- function(string, pattern, negate = FALSE) {
4949 regex = stri_detect_regex(string , pattern , negate = negate , opts_regex = opts(pattern ))
5050 )
5151}
52+
53+ # ' Detect the presence or absence of a pattern at the beginning or end of a
54+ # ' string.
55+ # '
56+ # ' Vectorised over `string` and `pattern`.
57+ # '
58+ # ' @inheritParams str_detect
59+ # ' @param pattern Pattern with which the string starts or ends.
60+ # '
61+ # ' The default interpretation is a regular expression, as described in
62+ # ' [stringi::stringi-search-regex]. Control options with [regex()].
63+ # '
64+ # ' Match a fixed string (i.e. by comparing only bytes), using [fixed()]. This
65+ # ' is fast, but approximate. Generally, for matching human text, you'll want
66+ # ' [coll()] which respects character matching rules for the specified locale.
67+ # '
68+ # ' @return A logical vector.
69+ # ' @seealso [str_detect()] which this function wraps when pattern is regex.
70+ # ' @export
71+ # ' @examples
72+ # ' fruit <- c("apple", "banana", "pear", "pinapple")
73+ # ' str_starts(fruit, "p")
74+ # ' str_starts(fruit, "p", negate = TRUE)
75+ # ' str_ends(fruit, "e")
76+ # ' str_ends(fruit, "e", negate = TRUE)
77+ str_starts <- function (string , pattern , negate = FALSE ) {
78+ switch (
79+ type(pattern ),
80+ empty = ,
81+ bound = stop(" boundary() patterns are not supported." ),
82+ fixed = stri_startswith_fixed(string , pattern , negate = negate , opts_fixed = opts(pattern )),
83+ coll = stri_startswith_coll(string , pattern , negate = negate , opts_collator = opts(pattern )),
84+ regex = {
85+ pattern2 <- paste0(" ^" , pattern )
86+ attributes(pattern2 ) <- attributes(pattern )
87+ str_detect(string , pattern2 , negate )
88+ }
89+ )
90+ }
91+
92+ # ' @rdname str_starts
93+ # ' @export
94+ str_ends <- function (string , pattern , negate = FALSE ) {
95+ switch (type(pattern ),
96+ empty = ,
97+ bound = stop(" boundary() patterns are not supported." ),
98+ fixed = stri_endswith_fixed(string , pattern , negate = negate , opts_fixed = opts(pattern )),
99+ coll = stri_endswith_coll(string , pattern , negate = negate , opts_collator = opts(pattern )),
100+ regex = {
101+ pattern2 <- paste0(pattern , " $" )
102+ attributes(pattern2 ) <- attributes(pattern )
103+ str_detect(string , pattern2 , negate )
104+ }
105+ )
106+ }
0 commit comments