Home: Perl Programming Help: Regular Expressions:
Testing for duplicate or invalid input



r0xx0rz
New User

Jan 10, 2005, 9:57 PM


Views: 10800
Testing for duplicate or invalid input

I am trying to check an equation for errors. Specifically, I need to test for duplicate input of operators (+,-,x,/,sqrt,exp) or an operator followed by =. Is it possible to do this using a regex? I have no idea how to begin.

Any help would be greatly appreciated.


davorg
Thaumaturge / Moderator

Jan 11, 2005, 5:55 AM


Views: 10797
Re: [r0xx0rz] Testing for duplicate or invalid input

If you can define the valid input then you'd have a good chance of defining a regex to check it.

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


kencl
User

Jan 12, 2005, 3:47 PM


Views: 10775
Re: [r0xx0rz] Testing for duplicate or invalid input


Code
if ($equation =~ /(\+|-|x|\/|sqrt|exp)  # find an operator 
\s* # optional space(s)
(\1|=) # matched operator or = sign
/x)
{
my ($operator, $duplicate) = ($1, $2);
if ($duplicate eq '=') {
print qq|Handle operator= error. Operator is "$operator"|;
} else {
print qq|Handle duplicate operator error. Operator is "$operator"|;
}
}


>> If you can't control it, improve it, correlate it or disseminate it with PERL, it doesn't exist!


r0xx0rz
New User

Jan 13, 2005, 12:47 PM


Views: 10759
Re: [kencl] Testing for duplicate or invalid input

Thanks fot the help.

This is what I ended up using:

$Equation=~/[0-9|\.|\(|\)]+(\+|\-|\/|x|Sqrt|Exp)(\+|\-|\/|x|Sqrt|Exp|=)/;

It seems to work. Smile


MrPJ
User

Jan 15, 2005, 4:16 PM


Views: 10724
Re: [r0xx0rz] Testing for duplicate or invalid input

The syntax is slightly off in places.


Code
 [0-9|\.|\(|\)]


You don't need pipe delimeters within a character class, nor do you need to escape meta characters (other than []).

So it would be written as...


Code
[0-9.()]



(This post was edited by MrPJ on Jan 15, 2005, 4:17 PM)


r0xx0rz
New User

Jan 18, 2005, 3:58 PM


Views: 10698
Re: [MrPJ] Testing for duplicate or invalid input


In Reply To


Code
[0-9.()]



That looks alot simpler. When I look at my other one, it looks so complicated, I can't believe I wrote it!

Thanks a bunch! Cool