10

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

  1. It can be blank means nothing is entered

  2. If specified it will always start with an operator + or - or * or / and will always be followed by a number that can have any number of digits and the number can be decimal(contains . in between the numbers) or integer(no '.' symbol within the number). examples : *0.9 , +22.36 , - 90 , / 0.36365

  3. It can be then followed by what is mentioned in point 2 (above line). examples : *0.9+5 , +22.36*4/56.33 , -90+87.25/22 , /0.36365/4+2.33

Please help me out.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Bibhu
  • 4,053
  • 4
  • 33
  • 63

4 Answers4

24

Something like this should work:

^([-+/*]\d+(\.\d+)?)*

Regexr Demo

  • ^ - beginning of the string
  • [-+/*] - one of these operators
  • \d+ - one or more numbers
  • (\.\d+)? - an optional dot followed by one or more numbers
  • ()* - the whole expression repeated zero or more times
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
kapa
  • 77,694
  • 21
  • 158
  • 175
  • @Jason McCreary - please have a look at the example, i meant the first '-' as a hypen not subtraction symbol. – Bibhu Jun 13 '12 at 06:38
  • @Bibhu Yeah at first I assumed it's a simple hyphen, and you wrote that it always starts with an operator followed by a number, so the minus would not fit there :). – kapa Jun 13 '12 at 06:39
  • @bažmegakapa - I want to allow the parenthesis in my regular expression, some thing like this *5-(4-8). I tried http://regexr.com?31e21 but was not successful in achieving, its also accepting *5-4-8) and *5-(4-8 which are not correct, need some help from you. – Bibhu Jul 03 '12 at 09:06
  • @Bibhu How about asking a question? :) – kapa Jul 03 '12 at 23:13
  • @bažmegakapa - I have added a question over here http://stackoverflow.com/questions/11323493/regular-expression-for-a-mathematical-expression – Bibhu Jul 04 '12 at 06:28
1

You could try generating such a regex using moo and such:

(?:(?:((?:(?:[ \t]+))))|(?:((?:(?:\/\/.*?$))))|(?:((?:(?:(?<![\d.])[0-9]+(?![\d.])))))|(?:((?:(?:[0-9]+\.(?:[0-9]+\b)?|\.[0-9]+))))|(?:((?:(?:(?:\+)))))|(?:((?:(?:(?:\-)))))|(?:((?:(?:(?:\*)))))|(?:((?:(?:(?:\/)))))|(?:((?:(?:(?:%)))))|(?:((?:(?:(?:\()))))|(?:((?:(?:(?:\)))))))

This regex matches any amount of int, float, braces, whitespace, and the operators +-*/%.

However, expressions such as 2+ would still be validated by the regex, so you might want to use a parser instead.

Nirvana
  • 405
  • 3
  • 15
0

If you want negative or positive expression you can write it like this>
^\-?[0-9](([-+/*][0-9]+)?([.,][0-9]+)?)*?$

And a second one
^[(]?[-]?([0-9]+)[)]??([(]?([-+/*]([0-9]))?([.,][0-9]+)?[)]?)*$

With parenthesis in expression but doesn't count the number you will need method that validate it or regex. // the method

 public static bool IsPairParenthesis(string matrixExpression)
    {
        int numberOfParenthesis = 0;
        foreach (char character in matrixExpression)
        {
            if (character == '(')
            {
                numberOfParenthesis++;
            }
            if (character == ')')
            {
                numberOfParenthesis--;
            }
        }

        if (numberOfParenthesis == 0)
        { return true; }
        return false;
    }
-1

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<String> 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;
    }