当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。