Joshua
Joshua

Reputation: 752

R: Replacing special characters in a text with gsub()

I would like to replace a series of smilies in a text. I've tried the following:

gsub(":)", "xxx", "some text >:) more text :) even more text", fixed = TRUE)

and

gsub("\\b:)\\b", "xxx", "some text >:) more text :) even more text")

That is, I would like to replace :) but not >:). Using \\b does the trick for text, but not this time fore the spacial characters that constitutes the smiley face.

Yes, I could use " :) ", but to me, this doesn't feel like the most elegant solution. What are my options to better control the replacement process?

Upvotes: 1

Views: 334

Answers (1)

Tyler Rinker
Tyler Rinker

Reputation: 109844

Try the following:

gsub("(^|(?<=\\s)):\\)", "xxx", ":) some text >:) more text :) even more text", perl=TRUE)
## [1] "xxx some text >:) more text xxx even more text"

Upvotes: 2

Related Questions