Forum Moderators: coopster & phranque

Message Too Old, No Replies

If Not a Match, do this

Regex question

         

StaceyJ

9:46 pm on Jan 26, 2011 (gmt 0)

10+ Year Member



I was wondering if it's possible to say something like

If this string DOESN'T match this, do this...like for instance

if !($string =~ m|>.*Widget<|) {
$string =~ s|>(.*)Widg<|>$1Widget<|;
}

That's a rough example, but it gives you the basic idea. I tried it and of course it wasn't very happy with me and gave me an error. Can you not use a negative match like that, or must I have an ELSE to go along with it? I was under the impression an ELSE wasn't required, but the error seemed to suggest otherwise.

janharders

10:32 pm on Jan 26, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



yeah, it's possible, in two ways:

if(!($string =~ m|>.*Widget<|)) { $string =~ s|>(.*)Widg<|>$1Widget<|; }

which is: if not(string matches foo)

if($string !~ m|>.*Widget<|) { $string =~ s|>(.*)Widg<|>$1Widget<|; }

which is: if string not matches foo

StaceyJ

10:56 pm on Jan 26, 2011 (gmt 0)

10+ Year Member



Ahhhh, thank you! I was so close. I searched and searched and came up with nothing helpful and I like to try to figure things out on my own before asking for help.

Question, jdMorgan has taught me a lot about efficiency with his htaccess regex examples, is one more efficient or a better way than the other?

Thank you again!

janharders

3:38 pm on Jan 27, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I really couldn't say, but I wouldn't be surprised if perl optimized ! =~ to !~. You could benchmark it, but I doubt you'd win much in either case.