From 6f85a068aa1cfa8f8a4e3616d56e422aa6d74d11 Mon Sep 17 00:00:00 2001 From: edward-burn <9583964+edward-burn@users.noreply.github.com> Date: Thu, 15 Aug 2024 14:00:30 -0700 Subject: [PATCH] define [[.stringr_pattern (#569) Fixes #529 --- NAMESPACE | 1 + NEWS.md | 3 +++ R/modifiers.R | 9 +++++++++ tests/testthat/test-modifiers.R | 7 +++++++ 4 files changed, 20 insertions(+) diff --git a/NAMESPACE b/NAMESPACE index 07f842ab..3f1bffc3 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -2,6 +2,7 @@ S3method("[",stringr_pattern) S3method("[",stringr_view) +S3method("[[",stringr_pattern) S3method(print,stringr_view) S3method(type,character) S3method(type,default) diff --git a/NEWS.md b/NEWS.md index 365fd68b..ff177e75 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # stringr (development version) +* Adds `[[.stringr_pattern` method to go along with existing `[.stringr_pattern` + method (@edward-burn, #569). + * In `str_replace_all()`, a `replacement` function now receives all values in a single vector. This radically improves performance at the cost of breaking some existing uses (#462). diff --git a/R/modifiers.R b/R/modifiers.R index d183ac0b..7783b807 100644 --- a/R/modifiers.R +++ b/R/modifiers.R @@ -227,6 +227,15 @@ type.default <- function(x, error_call = caller_env()) { ) } +#' @export +`[[.stringr_pattern` <- function(x, i) { + structure( + NextMethod(), + options = attr(x, "options"), + class = class(x) + ) +} + as_bare_character <- function(x, call = caller_env()) { if (is.character(x) && !is.object(x)) { # All OK! diff --git a/tests/testthat/test-modifiers.R b/tests/testthat/test-modifiers.R index 34495494..aa1624c8 100644 --- a/tests/testthat/test-modifiers.R +++ b/tests/testthat/test-modifiers.R @@ -36,3 +36,10 @@ test_that("subsetting preserves class and options", { x <- regex("a", multiline = TRUE) expect_equal(x[], x) }) + +test_that("stringr_pattern methods", { + ex <- coll(c("foo", "bar")) + expect_true(inherits(ex[1], "stringr_pattern")) + expect_true(inherits(ex[[1]], "stringr_pattern")) + +})