简体   繁体   English

正则表达式以评估和替换算术运算符

[英]Regular Expression to evaluate and replace arithmetic operators operators

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. 我认为必须对正则表达式进行更多的修改,以使其仅读取方括号中的“-”,但我应该有一些想法。

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 Ideone链接

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. 帮助提取正则表达式以&循环检测分号终止的C ++可能会为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM