1

I have an input string like this :

f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)

I want to get this output:

(x / (3*y)) * 54 = 64 / (7 * x) + ((2*x) / (y-6))

The rule: the parenthesis marked with 'f', remove the 'f' and the ',' mark have to change to /. If one of the sides contain an expresion it have to be put in to parenthesis f(2 , 2 + x) = (2 / (2 + x))

I have code that works for most test input but, in some test cases, it generates the wrong output:

line = sub(r"f\((.+?) *, *(.+?)\)", r"(\1 / \2)", (sub(r"f\((.+?[\+-/\*]+.+?) *, *(.+?)\)", r"f((\1),\2)", (sub(r"f\((.+?) *, *(.+?[\+-/\*]+.+?)\)", r"f(\1,(\2))", line)))))

This is the code I have written. As I mentioned, it works well, but for this line:

f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)

I get this result:

((x / (3*y)) * 54 = 64 / (7 * x) + (2*x) / (y-6))

One of the parentheses is in the wrong place. I have no idea what the problem is.

4
  • 3
    You're going to need to elaborate on the rules. It's not at all clear what you are trying to do. Commented Jun 6, 2014 at 16:55
  • can u post two to three strings like that. i can try generic for all Commented Jun 6, 2014 at 16:59
  • 1
    You try to put too many replaces in one line and can't identify where it breaks. The problem is .+? matches parens when it shouldn't, and you see that clearly with this compared to this. Commented Jun 6, 2014 at 17:18
  • It is better to ask questions about an approach, not exactly the code you need. You could also simplify your code so that people could understand it more easily. Commented Feb 18, 2020 at 17:06

1 Answer 1

3

Your regex is too complex.

If x and (x) doesn't matter you could simply use :

regex pattern : f\((\S+?),\s+(\S+)?\) and

replace it with : \( \(\1\) / \(\2\) \)

This will give

( (x) / (3*y) ) * 54 = 64 / (7 * x) + ( (2*x) / (y-6) )

for f(x, 3*y) * 54 = 64 / (7 * x) + f(2*x, y-6)

Sign up to request clarification or add additional context in comments.

1 Comment

It's meter x or (x), it must be x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.