0

i need a regular expression that would replace arithmetic operators in a given string. I need to be able to replace the operators with "|".

for instance,

String input = "5.0+9.0-(-2.0)";

String replace = input.replaceAll("[+-//*&&[^.]&&[^(-]]", "|");

in this instance i intend only to replace the operators outside the brackets. I think the regular expression has to be modified more to read only the "-" outside the brackets but i'm ought of ideas.

Grodriguez
  • 21,501
  • 10
  • 63
  • 107
user506574
  • 1
  • 1
  • 1

2 Answers2

1

If you just want to replace (and not evaluate) the arithmetic operators which are not in parenthesis you can try:

String replace = input.replaceAll("[-+*/](?![^(]*\\))","|");

Ideone Link

codaddict
  • 445,704
  • 82
  • 492
  • 529
0

This seems difficult to do with one regular expression. I think the best way is to extract the bracketed expressions and replace the arithmetic operations in the remaining string. Because regex can't cope with brackets.

For help with the extraction Regular expression to detect semi-colon terminated C++ for & while loops may help you.

Community
  • 1
  • 1
kasten
  • 602
  • 2
  • 6
  • 17