簡體   English   中英

用R中的標點符號替換字符串變量而不刪除其他字符串

[英]Replacing string variable with punctuation in R without removing other string

在 R 中,我無法替換帶有標點符號的子字符串。 即在字符串“r.Export”中,我試圖替換“r”。 用“報告”。 我用過 gsub,下面是我的代碼:

string <- "r.Export"
short <- "r."
replacement <- "Report."

gsub(short,replacement,string)

所需的輸出是:“Report.Export”但是 gsub 似乎替換了第二個 r,這樣輸出是:

Report.ExpoReport.

使用 sub() 也不是解決方案,因為我正在執行多個 gsub,有時要替換的字符串是:

short <- "o."

因此,無論如何, r.Export 中的 o 都會被替換,這將變得一團糟。

string <- "r.Export"
short <- "r\\."
replacement <- "Report."

gsub(short,replacement,string)

返回:

[1] "Report.Export"

或者,使用fixed=TRUE

string <- "r.Export"
short <- "r."
replacement <- "Report."

gsub(short,replacement,string, fixed=TRUE)

返回:

[1] "Report.Export"

說明:如果沒有fixed=TRUE參數, gsub需要一個正則表達式作為第一個參數。 並帶有正則表達式. 是“任何字符”的占位符。 如果你想要文字. (句號)你必須使用\\\\. (即轉義句點)或上述參數fixed=TRUE

由於您的模式中有字符 ( . ) 在正則表達式中具有特殊含義,因此請使用fixed = TRUE原樣匹配字符串。

gsub(short,replacement,string, fixed = TRUE)
#[1] "Report.Export"

我實際上可能會在此處添加單詞邊界和前瞻,以確保盡可能有針對性地匹配:

string <- "r.Export"
replacement <- "Report."
output <- gsub("\\br\\.(?=\\w)", replacement, string, perl=TRUE)
output

[1] "Report.Export"

這種方法確保我們只匹配r. r前面有空格或者是字符串的開頭時,以及當點后面是另一個詞時。 考慮句子The project r.Export needed a programmer. 我們不想替換最后的r. 在這種情況下。

我們可以使用sub

sub(short,replacement,string, fixed = TRUE)
#[1] "Report.Export"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM