Skip to content

Feature request: str_replace_n() to replace the nth match #583

@DanChaltiel

Description

@DanChaltiel

Hi, and thank you for your work on stringr!

I’d like to suggest a new function: str_replace_n(), which would allow replacing the nth match of a pattern.

This would cover common but currently awkward use cases, such as replacing only the last match or the second match.

Expected output:

str_replace_n("a-b-c-d", "-", "+", n = 1) #with n=1, we get the same as str_replace()
#> "a+b-c-d"

str_replace_n("a-b-c-d", "-", "+", n = 2)
#> "a-b+c-d"

str_replace_n("a-b-c-d", "-", "+", n = -1)
#> "a-b-c+d"

Would this kind of feature be aligned with the design goals of the package?

If not, would you consider at least re-exporting stringi::stri_replace_last()?

Thanks again for considering it!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions