rstringr

How to insert characters after a pattern using stringr?


I have a character vector

xx <- c ("AB", "BA", "CA")

I would like to insert the word "hello" after the first element, but only if this element is not A. I would like to get: "AB", "BhelloA", "ChelloA"

I have figured out how to reference the desired pattern after which I want the insertion: "(?=^)[^A]". But how do I instruct R (preferably in stringr package to insert the desired pattern)?


Solution

  • You were almost there, but the [^A] goes inside the lookaround.

    library(stringr)
    xx <- c ("AB", "BA", "CA")
    
    str_replace(xx, "(?<=^[^A])", "hello")
    #> [1] "AB"      "BhelloA" "ChelloA"
    

    Created on 2024-06-07 with reprex v2.1.0