Search code examples
androidexpressionfactorialinsertion

How to insert brackets only around an operand and the following factorial (!) operator in a mathematical expression?


User-entered expression: 2+3!-4

What I want to achieve: 2+(3!)-4

For this I understand that I can use 'replaceAll()' and replace all "!" with "!)". This solves the closing bracket insertion problem but I want to know how can I get "(" before the operand (in this case, 3) as it can be any number.

Thanks :)


Solution

  • You can use this regular expression /(\d+\!)/g to find the parts using a factorial. The implementation depends on what language you use.

    In Java it should be something like myString.replaceAll("(\d+\!)", "($1)"); The $1 is a backreference to the orignial pattern.