Skip to content

Commit f70c4ba

Browse files
authored
make detect helpers honor regex "|" operator (#340)
* make detect helpers honor regex "|" operator * update for hadley
1 parent faedc2d commit f70c4ba

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# stringr (development version)
22

3+
* Update `str_starts()` and `str_ends()` functions so they honor regex operator precedence. (@carlganz)
4+
35
* `word()` now returns all the sentence when using a negative `start` parameter
46
that is greater or equal than the number of words. (@pdelboca, #245)
57

R/detect.r

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ str_starts <- function(string, pattern, negate = FALSE) {
8282
fixed = stri_startswith_fixed(string, pattern, negate = negate, opts_fixed = opts(pattern)),
8383
coll = stri_startswith_coll(string, pattern, negate = negate, opts_collator = opts(pattern)),
8484
regex = {
85-
pattern2 <- paste0("^", pattern)
85+
pattern2 <- paste0("^(", pattern, ")")
8686
attributes(pattern2) <- attributes(pattern)
8787
str_detect(string, pattern2, negate)
8888
}
@@ -98,7 +98,7 @@ str_ends <- function(string, pattern, negate = FALSE) {
9898
fixed = stri_endswith_fixed(string, pattern, negate = negate, opts_fixed = opts(pattern)),
9999
coll = stri_endswith_coll(string, pattern, negate = negate, opts_collator = opts(pattern)),
100100
regex = {
101-
pattern2 <- paste0(pattern, "$")
101+
pattern2 <- paste0("(", pattern, ")$")
102102
attributes(pattern2) <- attributes(pattern)
103103
str_detect(string, pattern2, negate)
104104
}

tests/testthat/test-detect.r

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ test_that("str_starts works", {
3636
# Special typing of patterns.
3737
expect_true(str_starts("ab", fixed("A", ignore_case = TRUE)))
3838
expect_true(str_starts("ab", regex("A", ignore_case = TRUE)))
39+
40+
# Or operators are respected
41+
expect_true(str_starts("ab", "b|a"))
42+
expect_false(str_starts("ab", "c|b"))
3943
})
4044

4145
test_that("str_ends works", {
@@ -48,6 +52,10 @@ test_that("str_ends works", {
4852

4953
# Special typing of patterns.
5054
expect_true(str_ends("ab", fixed("B", ignore_case = TRUE)))
55+
56+
# Or operators are respected
57+
expect_true(str_ends("ab", "b|a"))
58+
expect_false(str_ends("ab", "c|a"))
5159
})
5260

5361

0 commit comments

Comments
 (0)