Skip to content
Merged
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
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@

* New `str_equal()` compares two character vectors using unicode rules,
and optionally ignores case (#381).

* `str_extract()` can now optionally extract a capturing group instead of
the complete match (#420).

* New `str_split_1()` is tailored for the special case of splitting up a single
string (#409).
Expand Down
13 changes: 11 additions & 2 deletions R/extract.r
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
#'
#' @inheritParams str_detect
#' @return A character vector.
#' @param group If supplied, instead of returning the complete match, will
#' return the matched text from the specified capturing group.
#' @seealso [str_match()] to extract matched groups;
#' [stringi::stri_extract()] for the underlying implementation.
#' @param simplify A boolean.
Expand All @@ -18,6 +20,10 @@
#' str_extract(shopping_list, "[a-z]{1,4}")
#' str_extract(shopping_list, "\\b[a-z]{1,4}\\b")
#'
#' str_extract(shopping_list, "([a-z]+) of ([a-z]+)")
#' str_extract(shopping_list, "([a-z]+) of ([a-z]+)", group = 1)
#' str_extract(shopping_list, "([a-z]+) of ([a-z]+)", group = 2)
#'
#' # Extract all matches
#' str_extract_all(shopping_list, "[a-z]+")
#' str_extract_all(shopping_list, "\\b[a-z]+\\b")
Expand All @@ -29,9 +35,12 @@
#'
#' # Extract all words
#' str_extract_all("This is, suprisingly, a sentence.", boundary("word"))
str_extract <- function(string, pattern) {
check_lengths(string, pattern)
str_extract <- function(string, pattern, group = NULL) {
if (!is.null(group)) {
return(str_match(string, pattern)[, group + 1])
}

check_lengths(string, pattern)
switch(type(pattern),
empty = stri_extract_first_boundaries(string, pattern, opts_brkiter = opts(pattern)),
bound = stri_extract_first_boundaries(string, pattern, opts_brkiter = opts(pattern)),
Expand Down
9 changes: 8 additions & 1 deletion man/str_extract.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions tests/testthat/test-extract.r
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,8 @@ test_that("str_extract extracts first match if found, NA otherwise", {
expect_length(word_1_to_4, length(shopping_list))
expect_equal(word_1_to_4[1], NA_character_)
})

test_that("can extract a group", {
expect_equal(str_extract("abc", "(.).(.)", group = 1), "a")
expect_equal(str_extract("abc", "(.).(.)", group = 2), "c")
})