Hello, I need to check for the correctness of the incoming string (to make protection from a fool). Which is of the following type: two (and only two) numbers and an operator (* / + -) between them, numbers can be negative, there can be as many spaces as you like, there should not be any other characters. I wish it was considered correct:

10+10 -10-10 -10*-10 и т.д. 

And such options were rejected:

 -10**10 10*10 10 10-*10 10-/10 10-10 - и т.д. 

I began to try to iterate through the loop and check IF-s for each character. But the impression was made that it would not be easy to do this, there would be a lot of code and it would be possible to take into account all variants of errors. Remembered about regular expressions.

Help please, is it possible to solve this with a regular expression. If so, how?

    1 answer 1

    Something like this (if - it should always be consistent with the number):

     -?\d+\s*[+\-\*\/]\s*-?\d+ 
    • Thank you very much, it helped a lot! Somewhat incorrectly responded to gaps in some places, so I added them. It turned out that something is Pattern.compile (" -? * \\ d + \\ s * [+ \\ - \ * \\ /] \\ s -? * \\ d +"); the expression is incorrectly displayed on the site) - fantastic
    • one
      @fantastic: to display correctly, put the symbol "` "on both sides of the code. - Nick Volynkin