Validate mathematical expressions using regular expression?

前端 未结 3 1428
醉酒成梦
醉酒成梦 2020-11-29 08:50

I want to validate mathematical expressions using regular expression. The mathematical expression can be this

  1. It can be blank means nothing is entered

3条回答
  •  情深已故
    2020-11-29 09:24

    This is java regex, but this is only if not have any braces

    [+\-]?(([0-9]+\.[0-9]+)|([0-9]+\.?)|(\.?[0-9]+))([+\-/*](([0-9]+\.[0-9]+)|([0-9]+\.?)|(\.?[0-9]+)))*
    

    Also this with braces in java code
    In this case I raplace (..) to number (..), should matches without brace pattern

        //  without brace pattern
        static Pattern numberPattern = Pattern.compile("[+\\-]?(([0-9]+\\.[0-9]+)|([0-9]+\\.?)|(\\.?[0-9]+))([+\\-/*](([0-9]+\\.[0-9]+)|([0-9]+\\.?)|(\\.?[0-9]+)))*");
        static Pattern bracePattern = Pattern.compile("\\([^()]+\\)");
    
        public static boolean matchesForMath(String txt) {
    
            if (txt == null || txt.isEmpty()) return false;
            txt = txt.replaceAll("\\s+", "");
            if (!txt.contains("(") && !txt.contains(")")) return numberPattern.matcher(txt).matches();
            if (txt.contains("(") ^ txt.contains(")")) return false;
            if (txt.contains("()")) return false;
    
            Queue toBeRematch = new ArrayDeque<>();
            toBeRematch.add(txt);
            while (toBeRematch.size() > 0) {
                String line = toBeRematch.poll();
                Matcher m = bracePattern.matcher(line);
                if (m.find()) {
                    String newline = line.substring(0, m.start()) + "1" + line.substring(m.end());
                    String withoutBraces = line.substring(m.start() + 1, m.end() - 1);
                    toBeRematch.add(newline);
                    if (!numberPattern.matcher(withoutBraces).matches()) return false;
                }
    
            }
            return true;
        }
    

提交回复
热议问题