How can I take the cosine argument with regexp

2 views (last 30 days)
I need to work with the arguments of the cosinus, I am working with a hughe matrix 10X10 with around 3 or 4 cosinus on each therm and I need to work only with the arguments.
I am trying to do with regexp.
A simplify example could be:
Take the arguments of the cosinus in the following expresion:
A=cos(-2/3*pi) - cos(phi*2 + pi/3);
What I did
str = 'cos(-2/3*pi) - cos(phi*2 + pi/3)';
expr = '[cos(\w)]';
[inputSignals]=regexp(str,expr)
The answer I have
inputSignals=[1 2 3 4 6 8 10 11 12 16 17 18 19 20 21 22 24 28 29 31 32]
What are the index from str to cos( 2 3 pi) and cos(phi 2 pi 3).
So I get the arguments without the symbols inside.
Here is my question:
¿ How can I write the expresion(expr) to have everything what is inside the brackets of the cosinus, write something instead of \w to have the full arguments?
PD: In the matrix I have more stuff with brackets, thats why I am asking Matlab to have cos(anything)

Accepted Answer

Kelly Kearney
Kelly Kearney on 24 May 2017
Perhaps I'm misunderstanding what you're looking for, but does the following match the pattern you want?
str = 'cos(-2/3*pi) - cos(phi*2 + pi/3)';
exp = '(?<=cos\()[0-9a-z\/\*\-\s\+]*(?=\))';
inputSignals = regexp(str, exp, 'match')
returns
inputSignals =
1×2 cell array
'-2/3*pi' 'phi*2 + pi/3'
This regex translates to "look for any group of letters, numbers, underscores, or +-*/ preceded by cos( and followed by ).
As Walter points out, it won't work if any of your cosine terms include parentheses themselves, i.e
str2 = 'cos(-2/3*pi) - cos((x+1)/2) + cos(phi*2 + pi/3)';
regexp(str2, expr, 'match')
returns (not what you want):
ans =
cell
'-2/3*pi) - cos((x+1)/2) + cos(phi*2 + pi/3'

More Answers (1)

Walter Roberson
Walter Roberson on 24 May 2017
No, you cannot do that with regular expressions -- not unless your regular expression engine has extensions to make it more powerful than true regular expressions. https://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns
MATLAB's regexp() does not have the extensions that would be needed.
The difficulty is in having to support an arbitrary number of nested brackets. Quoting Rafal from the above:
"The generated automaton will have a finite number of states, say k, so a string of k+1 opening braces is bound to have a state repeated somewhere (as the automaton processes the characters). The part of the string between the same state can be duplicated infinitely many times and the automaton will not know the difference.
In particular, if it accepts k+1 opening braces followed by k+1 closing braces (which it should) it will also accept the pumped number of opening braces followed by unchanged k+1 closing brases (which it shouldn't)."

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!