Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# stringr (development version)

* `str_like()` and `str_ilike()` now match regular expression metacharacters such as `.` and `*` literally (@taekop, #617).

# stringr 1.6.0

## Breaking changes
Expand Down
20 changes: 19 additions & 1 deletion R/detect.R
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,29 @@ str_ilike <- function(string, pattern) {
}

like_to_regex <- function(pattern) {
converted <- escape_like_metachars(pattern)
converted <- stri_replace_all_regex(
pattern,
converted,
"(?<!\\\\|\\[)%(?!\\])",
"\\.\\*"
)
converted <- stri_replace_all_regex(converted, "(?<!\\\\|\\[)_(?!\\])", "\\.")
paste0("^", converted, "$")
}

# Escapes regex metacharacters, except inside `[...]` groups or after `\`
escape_like_metachars <- function(pattern) {
out <- rep(NA_character_, length(pattern))
tokens <- stri_extract_all_regex(
pattern,
"(?s)\\[[^\\]]*\\]|\\\\.|.",
omit_no_match = TRUE
)
for (i in which(!is.na(pattern))) {
token <- tokens[[i]]
meta <- stri_detect_regex(token, "^[.^$*+?(){}|]$")
token[meta] <- paste0("\\", token[meta])
out[[i]] <- paste0(token, collapse = "")
}
out
}
19 changes: 19 additions & 0 deletions tests/testthat/test-detect.R
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,25 @@ test_that("str_ilike works", {
expect_snapshot(str_ilike("abc", regex("x")), error = TRUE)
})

test_that("str_like and str_ilike treat regex metacharacters literally", {
expect_equal(str_like(c("a.c", "abc"), "a.c%"), c(TRUE, FALSE))
expect_equal(str_ilike(c("A.C", "ABC"), "a.c%"), c(TRUE, FALSE))
expect_equal(str_like(c("a*c", "aac"), "a*c"), c(TRUE, FALSE))
expect_equal(str_like(c("a(b)c", "abc"), "a(b)c"), c(TRUE, FALSE))
expect_equal(str_like(c("a|b", "a"), "a|b"), c(TRUE, FALSE))
expect_equal(str_like(c("a+b", "aab"), "a+b"), c(TRUE, FALSE))
expect_equal(str_like(c("a?", "a"), "a?"), c(TRUE, FALSE))
expect_equal(str_like(c("a^b$", "ab"), "a^b$"), c(TRUE, FALSE))
expect_equal(str_like(c("a{2}", "aa"), "a{2}"), c(TRUE, FALSE))
expect_equal(str_like(c("a.b]", "axb]"), "a.b]"), c(TRUE, FALSE))
expect_equal(str_like(c("a(b)]", "abb]"), "a(b)]"), c(TRUE, FALSE))
expect_equal(str_like(c("f(x]", "fx]"), "f(x]"), c(TRUE, FALSE))
expect_equal(
str_like(c("a.b9", "axb9", "a.bz"), "a.b[0-9]"),
c(TRUE, FALSE, FALSE)
)
})

test_that("like_to_regex generates expected regexps", {
expect_equal(like_to_regex("ab%"), "^ab.*$")
expect_equal(like_to_regex("ab_"), "^ab.$")
Expand Down
Loading