substitute complex regular expression in R

Viewed 50

I am trying to substitute text to a word using gsub. For example:

My text is: I will add [USER=1234]@banana1[/USER] to the chat

My desired output is: I will add usermention to the chat

Basically , I want to substitute [USER=1234]@banana1[/USER] to usermention

I have tried the following code but unsuccessfully:


text=c("I ​will add [USER=1234]@banana1[/USER] to the chat")
replace_user=gsub("\\[user.*?\\/user\\]","usermention",text)

2 Answers

We can use

 sub("\\[.*\\]", "usermention", text)
[1] "I ​will add usermention to the chat"

You can use it with

> gsub("\\[user.*?/user]","usermention",text, ignore.case=TRUE)
[1] "I ​will add usermention to the chat"

Note that / is not any special in a TRE regex pattern, same is with ] outside a bracket expression, so no need to escape it.

Since you have USER and not user in the original string, you need the ignore.case=TRUE argument.

See the regex demo online.

See the R demo:

text=c("I will add [USER=1234]@banana1[/USER] to the chat"
gsub("\\[user.*?/user]","usermention",text, ignore.case=TRUE)
## => [1] "I will add usermention to the chat"
Related