A Perl regexp to validate arithmetic expressions

Can a Perl regexp validate arithmetic expressions? I say yes. Here is my Perl regexp to validate arifmetic expressions:

#!perl -w
use strict;
use re 'eval';
 
my @testexpr=(
# Valid arifmetic expressions
'+3',
'-(3/4+(-2-3)/3)',
'(-((3)))',
'-(+1+2)*(3/(1-2))/((-3))',
# Invalid (from the point of view of a human) arifmetic expressions
'2*-3',
'-(3/4+(-2-3)/3',
'(-((3)+))');
 
my $number=qr/\d+/; # pattern for a digit/variable
my $arifm;
# The modifier x is used to split the regexp to publish it in Web
$arifm=qr#[+-]?(?:$number|\((??{$arifm})\))(?:[*/](?:$number|\((??{$arifm})\)))*
   (?:[+-](?:$number|\((??{$arifm})\))(?:[*/](?:$number|\((??{$arifm})\)))*)*#x;
 
print /^$arifm$/ ? "Valid: $_\n" : "Invalid: $_\n" for (@testexpr);

Serge

# Valid arifmetic expressions
'+3',
'-(3/4+(-2-3)/3)',
'(-((3)))',
'-(+1+2)(3/(1-2))/((-3))',
'2
-3',
# Invalid (from the point of view of a human) arifmetic expressions
'-(3/4+(-2-3)/3',
'(-((3)+))');

Yes, 2*-3 is valid for Perl, Delphi and other compilers, but in mathematic we must write 2*(-3).

Serge

This sort validation is more a bison/lex/flex sort of thing, probably available in PERL, too. A small state machine in C could apply the rules, too, tracking parse state. However, I suspect even the most talented regex writer cannot decode infinitely complex state in a regex. Some things are easier done in stages, too, like parentheses and quote balance. Each milieu comes with it's own rules about what is an escape, how linefeeds are treated, punctuation of just white space.