Click to See Complete Forum and Search --> : Help Me Please:Regular Expression


kimskams80
11-18-2008, 10:06 AM
Hi Gurus

I have a string $str that may contain pattern like given below:

-1 +1 inverse -1 -1 inverse -1 -1 inverse inverse and

all are separated by spaces. Now I want to process it in steps:
1st I will remove DUALS i.e. -1 -1 by just one -1 i.e. above will become as:

-1 +1 inverse -1 inverse -1 inverse and

then I want to change the sign just following "inverse" and remove "inverse" itself i.e.

-1 +1 +1 +1 inverse and

now I will again process DUALS then it becomes

-1 +1 +1 inverse and

then -1 +1 inverse and

and then I will process this one and get -1 inverse and


I just want to know what regular expression I need to perform above replacements.... and it should work fine....because I was using

$str =~ s/1 -1/1/gi;

it was performing well but it was not ok for some string patterns (like it will even replace "-1 -1" as "-1" so I needed to have

$str =~ s/+1 -1/+1/gi;

but it does not work ..some problem I think....Can anybody help me out with this or with better solution..

Thanks

Sixtease
11-19-2008, 02:08 AM
I don't understand how you get

-1 inverse

from

-1 +1 inverse

But if you want to iteratively remove sequences of identical whitespace-delimited tokens, then apply inverses and end when it doesn't change, then this seems to work for me:
$new = "-1 +1 inverse -1 -1 inverse -1 -1 inverse inverse"; #input
until ($new eq $old) {
$old = $new;
$new =~ s/(\S+)(?: \1)+/$1/g;
$new=~ s/inverse ([-+])1/{"-"=>"+","+"=>"-"}->{$1}."1"/ge;
}
print $new;