tags:

views:

74

answers:

3

How to define regular expression of mathematical expression.please define a common regular expression for

5+4
5-3
5*6
6/2
A: 
^\d+[+*\-/]\d+$
Itay
`+` is not a meta character inside a character class - need not be escaped. `-` is a meta character inside a character class and need to be escaped unless it is the first or last character in the class. `^\d+[+*/-]\d+$` or `^\d+[+*\-/]\d+$` or `^\d+[-+*/]\d+$`
Amarghosh
you are right :) my bad
Itay
`(\d)+` will match and capture one digit at a time, so only the last digit is retained. If you want to capture the whole number, put the plus sign inside the parens: `(\d+)`; if you don't want to capture it, get rid of the parens because they're just creating a lot of extra work for the regex engine.
Alan Moore
The regex engines will look up and shout "Save us," and I'll whisper… "No."
jasonmp85
removed the -1 :)
Amarghosh
:) For some reason I tend to answer questions even if I don't really familiar with the subject. I hardly use regex in my code :)
Itay
Don't stop doing that.. that's how you learn - at least that's how I learned regex. Once learned, you'll start looking for a chance to use regex - at least I did.
Amarghosh
+4  A: 

Ok, here's one which might be a bit more complicated than you need (hey, it's a regex!)

/^\s*-?\d+(?:\.\d+)?(?:\s*[+*\/\-]\s*-?\d+(?:\.\d+)?)+(?:\s*=\s*-?\d+(?:\.\d+)?)?$/

It allows for one or more operations, decimal numbers, and optionally an "equals" part at the end.

5 + 7
3 * 2 - 8
80.31 + 12 / 6
5 * 7 - 2 = 33
nickf
`<nit-picking>` It doesn't support negative numbers `</nit-picking>`
Amarghosh
@Amarghosh: fixed!
nickf
A: 

The specification is vague, but here's a readable regex using meta-regexing approach in Java.

    String regex =
        "num(?:opnum)*"
            .replace("op", "\\s*[*/+-]\\s*")
            .replace("num", "\\s*[+-]?\\d+(?:\\.\\d+)?\\s*");
    String[] tests = {
        "5+4",          // true
        "5 - 3",        // true
        "5 * 6 - 4",    // true
        "3.14159 = 0",  // true
        "A = B",        // false
        "5+ -4",        // true
        "5 * +4",       // true
        "5++5",         // true
        "5+++5",        // false
        "5+5+"          // false
    };
    for (String test : tests) {
        System.out.println(test + " " + test.matches(regex));
    }

Numbers may include optional decimal part, and a +/- sign. There could be multiple equalities.

polygenelubricants