【发布时间】:2020-10-18 15:36:12
【问题描述】:
这个字符串操作问题已经避开了我的最大努力。我有一个字符串,例如
eg_str="[probability space](posts/probability space.md) is ... [Sigma Field](posts/Sigma Field.md)"
我想用下划线替换 ([wildcard].md) 通配符中的所有空格。我的第一个想法是使用 gsub 或 stringr 的 str_replace_all 将适当的子字符串传递给一个简单的函数。类似的东西
convert_space_to_underscore<-function(string){
return(str_replace(string," ","_"))
}
normal_eg_str<-gsub("\\((.+?)md\\)",paste0("(",convert_space_to_underscore("\\1"),"md)"),normal_eg_str)
或
normal_eg_str<-str_replace_all(document,"\\((.+?)md\\)",paste0("(",convert_space_to_underscore("\\1"),".md)"))
但是,当我运行这些时,似乎正在传递 convert_space_to_underscore 的参数,而不是输出,因为字符串返回不变(如果您在 paste0 组件中出错,说有 paste0("(",convert_space_to_underscore("\\1"),".m)"),那么字符串返回为
eg_str="[probability space](posts/probability space.m) is ... [Sigma Field](posts/Sigma Field.m)"
所以我很确定发生的事情是 str_replace_all 和 gsub 根本没有评估函数)。
有没有办法强制评估?这将是最理想的,因为它将允许正则表达式组件保持一定的可读性。但是,我也欢迎任何纯正则表达式解决方案——我的尝试都导致了贪婪的错误,无论我似乎在哪里撒? 和{0} 特殊字符。 (注意:会有一些匹配的子字符串有多个空格,例如[Dynklin's Pi Lambda](posts/dynklins pi lambda.md))
【问题讨论】: