Forum Moderators: coopster & phranque

Message Too Old, No Replies

Checking if either of two strings contain the same pattern

         

csdude55

9:22 am on Jan 7, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I recently realized that I have a lot of regexes that look like this:


if (
$string1 =~ /this|that|the other/ ||
$string2 =~ /this|that|the other/
) { $example = 20170107034814; }


Except that the pattern can often contain 50+ different potential matches, which means that I have two long lines that are almost duplicates... which means that there's twice the chance of an error in the coding.

Is there a way that I can make that shorter, easier to read, and less open to errors? I know I could do this:


$pattern = 'this|that|the other';

if (
$string1 =~ /$pattern/ ||
$string2 =~ /$pattern/
) { $example = 20170107034814; }


but I have a lot of elsif() statements, too, so that really just makes it more complicated than I'd want. I'm hoping that maybe there's a shortcut that I don't know, like this:


# This is just made up for an example, don't use it

if (
$string1
|| $string2 =~ /this|that|the other/
) { $example = 20170107034814; }


I'm using Perl version 5.10, so I'm not sure if I can use index() or ~~.

TIA!

upside

8:06 am on Jan 14, 2017 (gmt 0)

10+ Year Member



Since you are searching both strings, you could concatenate them like this:

if ($string1.$string2 =~ /this|that|the other/) { $example = 20170107034814; }

csdude55

9:12 am on Jan 14, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Awesome, my friend, that's exactly the type of shortcut I was hoping to find! I haven't tested it yet, but that'll be perfect and make my life about 10 times easier :D :D