![](/img/trans.png)
[英]R: How to replace space (' ') in string with a *single* backslash and space ('\ ')
[英]How to replace a string with a single backslash using gsub in R?
我喜歡編碼UTF-8字符串。 在我的數據中,字符用=
分隔,因為RI中的函數encoding
需要用\\x
分隔
string <- "=2E=30=31=20=52=C3=A9=70=6F=6E=64=65=75=72"
x <- gsub("=", "\x", string)
Encoding(x)
Encoding(x) <- "latin1"
x
我試圖添加一,二,三個反斜杠來逃避。 放在圓括號和方括號中。 添加引號。 將參數fixed=F
在這里 , 這里和這里閱讀,仍然不知道如何做。
預期產量:
.01 Répondeur
當我使用兩個反斜杠(如Wiktor所說)並使用cat()
檢查時,輸出中只有一個反斜杠,但僅當我手動更改時,它對encoding()
無效。
編輯:
例如,當我執行此操作時,它會放兩個反斜杠,而endcoding
不起作用:
> gsub("=", "\\x", string, fixed=TRUE)
[1] "\\x2E\\x30\\x31\\x20\\x52\\xC3\\xA9\\x70\\x6F\\x6E\\x64\\x65\\x75\\x72"
與亞歷山大·沃伊托夫(Aleksandr Voitov)的建議相同:
> gsub("=", "\\\\x", string)
[1] "\\x2E\\x30\\x31\\x20\\x52\\xC3\\xA9\\x70\\x6F\\x6E\\x64\\x65\\x75\\x72"
x <- "=2E=30=31=20=52=C3=A9=70=6F=6E=64=65=75=72" # string data
x <- strsplit(x, "=", useBytes = FALSE )[[1]] # split string
x <- x[nchar(x) > 0] # remove elements with 0 character length
使用strtoi
# convert string to integer and convert integer to raw and then to character
rawToChar( as.raw( strtoi(x, base = 16L) ) )
# [1] ".01 Répondeur"
?strtoi
文件頁面說
十六進制常量(前綴0x或0X)被解釋為以8和16為底
使用as.hexmode
將字符轉換為十六進制格式
rawToChar( as.raw( as.hexmode( x ) ) )
# [1] ".01 Répondeur"
您可以使用gsub("=", "\\\\x", string, fixed=TRUE)
將=
替換=
\\x
,然后parse
結果字符串:
string <- "=2E=30=31=20=52=C3=A9=70=6F=6E=64=65=75=72"
x <- parse(text = paste0("'", gsub("=", "\\x", string, fixed=TRUE), "'"))
x[[1]]
## => ".01 Répondeur"
請參閱在線R演示 。
這是另一個基於Unicode
包的解決方案:
> library(Unicode)
> string <- "=2E=30=31=20=52=C3=A9=70=6F=6E=64=65=75=72"
> x1 <- gsub("=", " U+", string, fixed=TRUE)
> y <- unlist(strsplit(trimws(x1), "\\s+"))
> intToUtf8(as.u_char_seq(y))
[1] ".01 Répondeur"
在這里,我將all =
替換為space + U+
,然后在修剪輸入后用1+個空格符號分割字符串。 intToUtf8(as.u_char_seq(y))
從Unicode字符序列創建Unicode字符串。
string <- "=2E=30=31=20=52=C3=A9=70=6F=6E=64=65=75=72"
x <- gsub("=", "\\\\x ", string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.