Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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 - Fatal编程技术网

R字符串匹配和替换

R字符串匹配和替换,r,regex,R,Regex,从字符串-theta[0]*x[0]*x[4]-theta[1]*x[1]开始,我想捕获theta[.]并替换为exp(theta[.]),给出最终结果如下: -exp(θ[0])*x[0]*x[4]-exp(θ[1])*x[1] 我如何在R中实现这一点 我通过在as之间进行匹配,尝试进行以下测试: p <- c("abba", "abcdab") gsub("\\(a[^a]*a\

从字符串
-theta[0]*x[0]*x[4]-theta[1]*x[1]
开始,我想捕获
theta[.]
并替换为
exp(theta[.])
,给出最终结果如下:

-exp(θ[0])*x[0]*x[4]-exp(θ[1])*x[1]

我如何在R中实现这一点

我通过在
a
s之间进行匹配,尝试进行以下测试:

p <- c("abba", "abcdab")                                                      
gsub("\\(a[^a]*a\\)", "|\\1|", p)
但结果是

[1] "abba"   "abcdab"
什么是实现所需结果的适当正则表达式

提前感谢。

我们可以使用

gsub("(theta\\[\\d+\\])", "exp(\\1)", "-theta[0] * x[0] * x[4] -theta[1] * x[1]")
# [1] "-exp(theta[0]) * x[0] * x[4] -exp(theta[1]) * x[1]"
它将
theta[.]
位置的任意数字匹配,并用
exp(theta[.])
替换它

您的尝试很好,您不需要跳过括号,因为括号表示您稍后要提及的组:

gsub("(a[^a]*a)", "|\\1|", p)
# [1] "|abba|"   "|abcda|b"
gsub("(a[^a]*a)", "|\\1|", p)
# [1] "|abba|"   "|abcda|b"