我有一个XML代码,我想替换其中的某些内容。 如果有"\d{4}s</w:t>"
我想用"<w:rPr><w:keepNext/>"
替换之前最后一次出现的"<w:rPr>"
,我不知道怎么做。 我尝试的是"str_replace_all(Text, "(<w:rPr>.*?)(\d{4}s</w:t>)", "\1<w:keepNext/>\2")"
但这并不能取代最后一次出现的"<w:rPr>"
。
我之前问过一个类似的问题,但它被关闭了,因为它太相似了,无法在两个字符串之间找到最短的匹配项。 但这对我没有帮助。
编辑: 下面是一个类似的例子:str_replace_all("hallohallohallo text bye hallohallo text2 bye", "(hallo)(.*?bye)", "\1,\2")
导致"hallo,hallohallo text bye hallo,hallo text2 bye"
,我想要"hallohallohallo, text bye hallohallo, text2 bye"
我不确定我是否完全遵循XML匹配(我不太精通解析/选择XML(,但是对于类似的示例,使用+
字符创建一个或多个的组。
myText <- "hallohallohallo text bye hallohallo text2 bye"
str_replace_all(myText, "((hallo)+)(.*?bye)", "\1,\3")
#> [1] "hallohallohallo, text bye hallohallo, text2 bye"
```
我发现的解决方法:
str_split(Text, "(?<=<w:pPr>)") %>%
unlist %>%
modify_if(~ str_detect(.x, "\d{4}s</w:t>"), ~ str_c("<w:keepNext/>", .x)) %>%
str_c(collapse = "")