The nth instance of an pattern will cover a series of character indices. These functions tell you which indices those are. These functions are vectorised over all arguments.

str_locate_nth(string, pattern, n)

str_locate_first(string, pattern)

str_locate_last(string, pattern)

Arguments

string

A character vector.

pattern

The pattern to look for.

The default interpretation is a regular expression, as described in stringi::about_search_regex.

To match a without regular expression (i.e. as a human would), use coll(). For details see stringr::regex().

n

A vector of integerish values. Must be either length 1 or have length equal to the length of string. Negative indices count from the back: while n = 1 and n = 2 correspond to first and second, n = -1 and n = -2 correspond to last and second-last. n = 0 will return NA.

Value

A two-column matrix. The \(i\)th row of this matrix gives the start and end indices of the \(n\)th instance of pattern in the \(i\)th element of string.

Details

  • str_locate_first(...) is just str_locate_nth(..., n = 1).

  • str_locate_last(...) is just str_locate_nth(..., n = -1).

See also

Other locators: str_locate_braces()

Examples

str_locate_nth(c("abcdabcxyz", "abcabc"), "abc", 2)
#>      start end
#> [1,]     5   7
#> [2,]     4   6
str_locate_nth(
  c("This old thing.", "That beautiful thing there."),
  "\\w+", c(2, -2)
)
#>      start end
#> [1,]     6   8
#> [2,]    16  20
str_locate_nth("abc", "b", c(0, 1, 1, 2))
#>      start end
#> [1,]    NA  NA
#> [2,]     2   2
#> [3,]     2   2
#> [4,]    NA  NA
str_locate_first("abcxyzabc", "abc")
#>      start end
#> [1,]     1   3
str_locate_last("abcxyzabc", "abc")
#>      start end
#> [1,]     7   9