Sam
Sam

Reputation: 261

add characters before special characters in a string

I would like to add some characters to a string before a special character "(" and after the special character ")"

The position of "(" and ")" changes from one string to the next.

If it helps, I tried several ways, but I don't know how to piece it back together.

a <- "a(b"
grepl("[[:punct:]]",  a) #special character exists
x <- "[[:punct:]]" 
image <- str_extract(a, x) #extract special character
image

e.g.

"I want to go out (i.e. now). "

And the result to look like:

"I want to go out again (i.e. now) thanks."

I want to add "again" and "thanks" to the sentence.

Thank you for helping!

Upvotes: 1

Views: 628

Answers (2)

akrun
akrun

Reputation: 887038

We can use sub. Match the characters inside the brackets including the brackets, capture it as a group, and we replace it with adding 'again' followed by the backreference of the captureed group (\\1) followed by 'thanks'

sub("(\\([^)]+\\))\\..*", "again \\1 thanks.", str1)
#[1] "I want to go out again (i.e. now) thanks."

Or using two capture groups

sub("(\\([^)]+\\))(.*)\\s+", "again \\1 thanks\\2", str1)
#[1] "I want to go out again (i.e. now) thanks."

data

str1 <- "I want to go out (i.e. now). "

NOTE: Using only base R

Upvotes: 2

Luiz Rodrigo
Luiz Rodrigo

Reputation: 936

Use str_replace

 library(stringr)
 str_replace("I want to go out (i.e. now).", "\\(", "again (") %>%
   str_replace("\\)", ") thanks")

Upvotes: 3

Related Questions