Add backslash before a character in a string [duplicate]

妖精的绣舞 提交于 2019-12-12 05:31:11

问题


I want to add the "\" character to my string using R. My string looks like this:

q <- "U0E2BU0E25"

I want to add a backslash before the letter "U" so the result would look like this:

\U0E2B\U0E25

I have tried using gsub:

gsub("U", "\U", q)

but received an error:

Error: '\U' used without hex digits in character string starting ""\U"


回答1:


We need to escape the backslash.

gsub("U", "\\\\U", q)
#[1] "\\U0E2B\\U0E25"

Note that there is an escape for the backslash. It becomes evident when we print it

cat(gsub("U", "\\\\U", q), "\n")
#\U0E2B\U0E25 


来源:https://stackoverflow.com/questions/44366812/add-backslash-before-a-character-in-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!