當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R stringr str_replace 用新文本替換匹配項


str_replace() 替換第一個匹配項; str_replace_all() 替換所有匹配項。

用法

str_replace(string, pattern, replacement)

str_replace_all(string, pattern, replacement)

參數

string

輸入向量。或者是一個字符向量,或者是可強製轉換為一個的東西。

pattern

要尋找的模式。

默認解釋是正則表達式,如 stringi::about_search_regex 中所述。使用 regex() 控製選項。

要在 string 的每個元素中執行多次替換,請傳遞提供一個命名向量 (c(pattern1 = replacement1) )。

使用 fixed() 匹配固定字符串(即僅比較字節)。這很快,但是是近似值。一般來說,為了匹配人類文本,您需要coll(),它尊重指定區域設置的字符匹配規則。

replacement

替換值,通常是單個字符串,但也可以是與 stringpattern 長度相同的向量。 \1\2 等形式的引用將替換為相應匹配組的內容(由 () 創建)。

或者,提供一個函數,每個匹配項(從右到左)都會調用該函數一次,並且其返回值將用於替換匹配項。

string /pattern /replacement 長度相同的字符向量。

也可以看看

str_replace_na() 將缺失值轉換為"NA"; stri_replace() 用於底層實現。

例子

fruits <- c("one apple", "two pears", "three bananas")
str_replace(fruits, "[aeiou]", "-")
#> [1] "-ne apple"     "tw- pears"     "thr-e bananas"
str_replace_all(fruits, "[aeiou]", "-")
#> [1] "-n- -ppl-"     "tw- p--rs"     "thr-- b-n-n-s"
str_replace_all(fruits, "[aeiou]", toupper)
#> [1] "OnE ApplE"     "twO pEArs"     "thrEE bAnAnAs"
str_replace_all(fruits, "b", NA_character_)
#> [1] "one apple" "two pears" NA         

str_replace(fruits, "([aeiou])", "")
#> [1] "ne apple"     "tw pears"     "thre bananas"
str_replace(fruits, "([aeiou])", "\\1\\1")
#> [1] "oone apple"     "twoo pears"     "threee bananas"

# Note that str_replace() is vectorised along text, pattern, and replacement
str_replace(fruits, "[aeiou]", c("1", "2", "3"))
#> [1] "1ne apple"     "tw2 pears"     "thr3e bananas"
str_replace(fruits, c("a", "e", "i"), "-")
#> [1] "one -pple"     "two p-ars"     "three bananas"

# If you want to apply multiple patterns and replacements to the same
# string, pass a named vector to pattern.
fruits %>%
  str_c(collapse = "---") %>%
  str_replace_all(c("one" = "1", "two" = "2", "three" = "3"))
#> [1] "1 apple---2 pears---3 bananas"

# Use a function for more sophisticated replacement. This example
# replaces colour names with their hex values.
colours <- str_c("\\b", colors(), "\\b", collapse="|")
col2hex <- function(col) {
  rgb <- col2rgb(col)
  rgb(rgb["red", ], rgb["green", ], rgb["blue", ], max = 255)
}

x <- c(
  "Roses are red, violets are blue",
  "My favourite colour is green"
)
str_replace_all(x, colours, col2hex)
#> [1] "Roses are #FF0000, violets are #0000FF"
#> [2] "My favourite colour is #00FF00"        
源代碼:R/replace.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Replace matches with new text。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。