#!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 call) 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);