2

I have an awful large expression that expresses the power in terms of the ** operator and need to convert it to code that uses the pow function. That is, I look for a regular expression for finding and replacing terms like a*b**N*d by a*pow(b,N), where N is an integer.

Here, a, b, and c are terms that may contain xy*-+() and integers and a*, *d may not be present.

I am somehow stuck with escaping all these characters. I am ready to invest some manual postprocessing, so the regex should be robust but not necessarily perfect.

EDIT: As Kent pointed out, there is a difficulty when b contains nested brackets. In my case there are no nested brackets. The terms are all of the form as given in the comment below.

Jan
  • 4,932
  • 1
  • 26
  • 30
  • does it mean `a+(i+(x*(m-n))+j)**p` will be converted into `a+pow( (i+(x*(m-n))+j),p)` ? – Kent Mar 04 '13 at 10:10
  • 1
    I feel that this is not the job for regex... – Kent Mar 04 '13 at 10:15
  • Yes. However, the terms rather look like `4*y**2*(-2*x + 1)*(-y + 1)**2` . What do you suggest? – Jan Mar 04 '13 at 10:23
  • it can be solved easily if there is maximum one pair of parens surrounding the term, without nesting -- see my updated answer – nl_0 Mar 04 '13 at 11:01

3 Answers3

1

If I understand you correctly, you can try using regex grouping to isolate the categories to extract:

So this is the regex:

(a\*)(b)\*{2}(N)\*d

You can extract the groups like so:

\1pow(\2,\3)

The reference groups are:

\1 = (a\*)
\2 = (b)
\3 = (N)
1

You can try this

Regex:(\([0-9xy*-]+\)|[0-9xy]+)\*\*([0-9]+)

Replace With:pow($1,$2) or pow(\1,\2)

Anirudha
  • 32,393
  • 7
  • 68
  • 89
  • K, it works! I only had to omit the plusses and escape the (). But that might be due to the vim 'magic'. – Jan Mar 04 '13 at 10:22
  • 1
    this won't work for nested brackets. e.g. in my comment. @Jan you should clearly define, what case in your real file, what not. btw, vim has `very magic` which could save some escapes. – Kent Mar 04 '13 at 10:29
  • Mmm. Sorry for that. I don't have nested brackets in my expressions. – Jan Mar 04 '13 at 10:38
1

It seems like this problem cannot be solved generally by regexes, because you need to balance parens somehow -- and this is the task for a parser.

Something like this will do the job where the are no parens: %s/\(x\|y\|\d\+\)\*\*\(\d\+\)/pow(\1,\2)/gc.

And something like this, if there may be only one pair of parens surrounding the term: %s/\(([xy0-9+-\* ]\+)\|x\|y\|\d\+\)\*\*\(\d\+\)/pow(\1,\2)/gc

BTW it reminds me of this question a bit =)

Community
  • 1
  • 1
nl_0
  • 391
  • 1
  • 6