str_replace:根据通配符值 [A-Z] 进行替换

str_replace: replacement depending on wildcard value [A-Z]

我有一些字符串包含模式“of”,后跟一个没有空格的大写字母(在正则表达式中:“of[A-Z]”)。我想添加空格,例如“PrinceofWales”应该变成“Prince of Wales”等等)。但是,我找不到如何将匹配的 [A-Z] 的值添加到替换值中:

library(tidyverse) 

str_replace("PrinceofWales", "of[A-Z]", " of [A-Z]")
# Gives: Prince of [A-Z]ales
# Expected: Prince of Wales

str_replace("DukeofEdinburgh", "of[A-Z]", " of [A-Z]")
# Gives: Duke of [A-Z]dinburgh
# Expected: Duke of Edinburgh

谁能赐教一下? :)

它需要被捕获为一个组 (([A-Z])) 并替换为捕获组的反向引用 (\1) 即 regex 解释在 pattern 而不是 replacement

stringr::str_replace("PrinceofWales", "of([A-Z])", " of \1")
[1] "Prince of Wales"

根据?str_replace

replacement - A character vector of replacements. Should be either length one, or the same length as string or pattern. References of the form , , etc will be replaced with the contents of the respective matched group (created by ()).


或者另一种选择是正则表达式环视

stringr::str_replace("PrinceofWales", "of(?=[A-Z])", " of ")
[1] "Prince of Wales"