Matlab中使用regexp的递归技巧 [英] Recursive tricks with regexp in Matlab
问题描述
我试图用regexprep
解决问题-给了我一个代表函数的字符串;它包含如下模式:'sin(arcsin(f))'
其中f
-任何子字符串;我需要用简单的'f_2'
替换它.除非遇到这样的字符串,否则我会成功使用regexprep
:
I tried to use regexprep
to solve a problem - I'm given a string, that represents a function; it contains a patterns like these: 'sin(arcsin(f))'
where f
- any substring; and I need to replace it with simple 'f_2'
. I successfully used regexprep
unless I face with such string:
str = 'sin(arcsin(sin(arcsin(f_2))))*x^2';
str = regexprep(str, 'sin\(arcsin\((\w*)\)\)','$1');
它返回
str =
sin(arcsin(f_2))*x^2
但是我希望它成为
str =
f_2*x^2
有什么办法可以解决(除了明显的for循环解决方案).
Is there any way to solve it (except obvious solution with for-loops).
推荐答案
我无法对此进行测试,但是我认为我找到了一个表达式,可以多次调用该表达式以完成您所要求的操作;每次它将从方程式中剥离"一对sin(arcsin())
对.一旦停止更改,就完成了.
I was not able to test this, but I thinkg I found an expression that you can call multiple times to do what you asked for; each time it will "strip" one sin(arcsin())
pair out of your equation. Once it stops changing, you're done.
(.*)sin\(arcsin\((.*(\(.*?\))*)(\)\).*$)
以下是一些Matlab代码,展示了其工作方式:
Here is some Matlab code that shows how this might work:
str = 'sin(arcsin(sin(arcsin(f_2))))*x^2';
regex = (.*)sin\(arcsin\((.*(\(.*?\))*)(\)\).*$);
oldlength = 0
newlength = length(str)
while (newlength != oldlength)
oldlength = newlength;
str = regexprep(str, regex,'$1$2');
newlength = length(str);
end
正如我所说-我无法测试.让我知道您是否对此有任何疑问.
As I said - I could not test this. Let me know if you have any problems with this.
正则表达式的演示
这篇关于Matlab中使用regexp的递归技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!