Perl Regex Guide: Match, Replace & Extract

In Perl, you can use regular expressions to perform string matching and replacement operations. Here are some basic examples of regular expression operations.

  1. String matching:
my $str = "Hello, World!";
if ($str =~ /Hello/) {
    print "String contains 'Hello'\n";
}
  1. Replacing strings:
my $str = "Hello, World!";
$str =~ s/Hello/Hi/;
print "$str\n";  # 输出 "Hi, World!"
  1. Extract the matching content.
my $str = "The price is $100";
if ($str =~ /(\$\d+)/) {
    my $price = $1;
    print "Price: $price\n";  # 输出 "Price: $100"
}
  1. Match in a loop using regular expressions.
my $str = "apple,banana,orange";
while ($str =~ /(\w+)/g) {
    print "$1\n";
}

The above are some basic examples of regular expression operations, which can be flexibly applied to string processing according to specific needs in practical applications.

bannerAds