Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将函数传递给基于R正则表达式的工具_R_Regex_Gsub_Stringr - Fatal编程技术网

将函数传递给基于R正则表达式的工具

将函数传递给基于R正则表达式的工具,r,regex,gsub,stringr,R,Regex,Gsub,Stringr,这个字符串操作问题逃避了我的最大努力。我有一根绳子 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_un

这个字符串操作问题逃避了我的最大努力。我有一根绳子

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)
所以我很确定现在发生的事情是str_replace_all和gsub根本没有评估函数)

有没有办法强制评估?这将是最理想的,因为它允许regex组件保持一定的可读性。然而,我也欢迎任何纯正则表达式的解决方案——我的尝试都会导致贪婪的错误,无论我在哪里散布
{0}
特殊字符。(注意:将有一些匹配的子字符串具有多个空格,例如
[Dynklin's Pi Lambda](posts/dynklins Pi Lambda.md)

您可以使用

库(stringr)
例如[1]“[probability space](posts/probability_space.md)是…[Sigma Field](posts/Sigma_Field.md)”

注意:要用一个下划线替换一个或多个空白块,您需要在
gsub
中使用正则表达式:
gsub(“\\s+”,“ux)”

将查找

  • \(
    -从
    开始(
  • [^()]+
    -有一个或多个字符,而不是
  • \.md
    -a
    .md
    字符串
  • \)
    -并以
    结尾)
然后,匹配项被传递给一个匿名函数,该函数用一个
(带有
gsub(“,“,”,x,fixed=TRUE)
)替换每个常规空格

基本R解决方案(可读性较差,但使用普通正则表达式):

eg_str
normal_eg_str<-str_replace_all(document,"\\((.+?)md\\)",paste0("(",convert_space_to_underscore("\\1"),".md)"))
eg_str="[probability space](posts/probability space.m) is ... [Sigma Field](posts/Sigma Field.m)"