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);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: RFC: Perl regex to validate arithmetic expressions
by JavaFan (Canon) on Feb 21, 2011 at 23:14 UTC | |
|
Re: RFC: Perl regex to validate arithmetic expressions
by Fox (Pilgrim) on Feb 21, 2011 at 16:57 UTC | |
|
Re: RFC: Perl regex to validate arithmetic expressions
by mellon85 (Monk) on Feb 21, 2011 at 18:53 UTC | |
by JavaFan (Canon) on Feb 22, 2011 at 09:58 UTC | |
|
Re: RFC: Perl regex to validate arithmetic expressions
by spx2 (Deacon) on Mar 15, 2011 at 16:43 UTC |