How do I search and replace with "OR" condition

Viewed 55

This is a trivial issue, but I hope someone can point me to the right way to do it. I have a string "Thunderstorms" which I replace with "T/storms".

s/Thunderstorms/T\/Storms/gi

It so happens that "Thunderstorms" is sometimes written as "Thunder Storms". Instead of writing two search and replace commands, I am looking for replacing "Thunderstorms" or "Thunder storms" with "T/Storms" in one command.

2 Answers

You can use \s* to match zero or more whitespaces:

use warnings;
use strict;

while (<DATA>) {
    s{Thunder\s*storms}{T/Storms}gi;
    print;
}

__DATA__
Thunderstorms
Thunder Storms
Thunder storms

Outputs:

T/Storms
T/Storms
T/Storms

I used different delimeters for the substitution operator (s{}{}) to avoid escaping the /.

use |.

s/Thunderstorms|Thunder\sStorms/T\/Storms/gi

sample code:

use strict;
use warnings;

my $str = 'Thunderstorms foo Thunder Storms bar';
$str =~ s/Thunderstorms|Thunder\sStorms/T\/Storms/gi;
print $str;
Related