My linux world » Perl – Regular expression

Perl - Regular expression


Contents

Capture string elements

my $string = "hello world";
 
if($string=~/^(\w+)\s+(\w+)$/) {
  my firstWord = $1;
  my secondWord = $1;
}

Or you can capture quickly if you are sure that the regular expression match :

$string=~/^(\w+)\s+(\w+)$/;
my firstWord = $1;
my secondWord = $1;

Case insensitive

To be case insensitiv, you have to add ‘i’ in your regular expression :

if($string=~/^K(.*)$/i) {
   # word can start with 'K' or 'k'
   my $result = $1;
}

Iterate

my $string = "hello world";
 
while($string=~/(\w)/g) {
  my $result = $1;
}

Substitution

my $string = "hello world";
 
$string=~s/\s+/,/g;
 
print "$string\"n;
# $> hello,world

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.