Sorry, I'm not a native English speaker.
Professional Perl programmers doubt that with one regex can validate arithmetic expressions, because of unlimited level of nested parentheses, and they use special Perl modules for this purpose. I wrote such regex. To do this, I used simple and elegant method by which you can write a similar complex expressions. I wrote an article about it, but unfortunately not in English ...
Here's my example:
#!perl -w
use strict;
use re 'eval';
# Validation of arithmetic expressions like +1*(2-3/(4*5))
# Author: Serge Melnikov (www.cronc.com)
my @testexpr=(
# Valid arithmetic expressions:
'+3',
'-(3/4+(-2-3)/3)',
'(-((3)))',
'-(+1+2)*(3/(1-2))/((-3))',
# Invalid (from the point of view of a human or mathematical notation)
+ arithmetic expressions:
'2*-3', # in math we must write 2*(-3)
'-(3/4+(-2-3)/3',
'(-((3)+))');
my $number=qr/\d+/; # the regex for a term (number/variable/function c
+all)
my $arithm;
# The x modifier used only to split the long regex to publish it
$arithm=qr#[+-]?(?:$number|\((??{$arithm})\))(?:[*/](?:$number|\((??{$
+arithm})\)))*
(?:[+-](?:$number|\((??{$arithm})\))(?:[*/](?:$number|\((??{$arithm
+})\)))*)*#x;
print /^$arithm$/ ? "Valid: $_\n" : "Invalid: $_\n" for (@testexpr);