fork download
  1. // Simple test to validate expression
  2. // Example: <number> <operator> <number> <=>
  3. // 1 * 5 =
  4.  
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8. class ExpressionValidator
  9. {
  10. public static boolean isValidExpression( final String exp )
  11. {
  12. final String regex = "\\d+\\s*[*|/|+|-]\\s*\\d+\\s*[=]";
  13. final Pattern pattern = Pattern.compile( regex );
  14. final Matcher matcher = pattern.matcher( exp.trim() );
  15. return matcher.find();
  16. }
  17.  
  18. public static void main( final String[] args )
  19. {
  20. final String[] expressions =
  21. {
  22. " 1 + 2 =",
  23. " 3 * 5 =",
  24. "12 + 10 =",
  25. " 33 = 25 ",
  26. " +65 65 ",
  27. "45 666 ="
  28. };
  29.  
  30. for ( final String exp : expressions )
  31. {
  32. System.out.println( "[" + exp + "] >> " + isValidExpression( exp ) );
  33. }
  34. }
  35. }
Success #stdin #stdout 0.1s 27864KB
stdin
Standard input is empty
stdout
[ 1 +  2 =] >> true
[ 3 *  5 =] >> true
[12 + 10 =] >> true
[ 33 = 25 ] >> false
[ +65  65 ] >> false
[45 666  =] >> false