diff --git a/NEWS.md b/NEWS.md index f4919912..0b87dc41 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # stringr (development version) +* Update `str_starts()` and `str_ends()` functions so they honor regex operator precedence. (@carlganz) + * `word()` now returns all the sentence when using a negative `start` parameter that is greater or equal than the number of words. (@pdelboca, #245) diff --git a/R/detect.r b/R/detect.r index 4201d4cf..9851d9d7 100644 --- a/R/detect.r +++ b/R/detect.r @@ -82,7 +82,7 @@ str_starts <- function(string, pattern, negate = FALSE) { fixed = stri_startswith_fixed(string, pattern, negate = negate, opts_fixed = opts(pattern)), coll = stri_startswith_coll(string, pattern, negate = negate, opts_collator = opts(pattern)), regex = { - pattern2 <- paste0("^", pattern) + pattern2 <- paste0("^(", pattern, ")") attributes(pattern2) <- attributes(pattern) str_detect(string, pattern2, negate) } @@ -98,7 +98,7 @@ str_ends <- function(string, pattern, negate = FALSE) { fixed = stri_endswith_fixed(string, pattern, negate = negate, opts_fixed = opts(pattern)), coll = stri_endswith_coll(string, pattern, negate = negate, opts_collator = opts(pattern)), regex = { - pattern2 <- paste0(pattern, "$") + pattern2 <- paste0("(", pattern, ")$") attributes(pattern2) <- attributes(pattern) str_detect(string, pattern2, negate) } diff --git a/tests/testthat/test-detect.r b/tests/testthat/test-detect.r index 0bbed020..56d3c7d5 100644 --- a/tests/testthat/test-detect.r +++ b/tests/testthat/test-detect.r @@ -36,6 +36,10 @@ test_that("str_starts works", { # Special typing of patterns. expect_true(str_starts("ab", fixed("A", ignore_case = TRUE))) expect_true(str_starts("ab", regex("A", ignore_case = TRUE))) + + # Or operators are respected + expect_true(str_starts("ab", "b|a")) + expect_false(str_starts("ab", "c|b")) }) test_that("str_ends works", { @@ -48,6 +52,10 @@ test_that("str_ends works", { # Special typing of patterns. expect_true(str_ends("ab", fixed("B", ignore_case = TRUE))) + + # Or operators are respected + expect_true(str_ends("ab", "b|a")) + expect_false(str_ends("ab", "c|a")) })