Search code examples
rregexstringmatching

R regex match beginning and middle of a string


I have a vector of strings:

A <- c("Hello world", "Green 44", "Hot Beer", "Bip 6t")

I want to add an asterisk (*) at the beginning and at the end of every first word like this:

"*Hello* world", "*Green* 44", "*Hot* Beer", "*Bip* 6t"

Make sense to use str_replace() from stringr. However, I am struggling with regex to match the first word of each string.

The best achievement ended up with:

str_replace(A, "^([A-Z])", "*\\1*"))
"*H*ello world", "*G*reen 44", "*H*ot Beer", "*B*ip 6t"

I might expect to be a straightforward task, but I am not getting along with regex.

Thanks!


Solution

  • You were almost there

    str_replace(A, "(^.*) ", "*\\1* ")
    #> [1] "*Hello* world" "*Green* 44"    "*Hot* Beer"    "*Bip* 6t"