Home Perl Regex

Modifiers

 
e Evaluate the replacement side as an expression
i Turn off case sensitivity
m Treat a string as multuple lines. Let ^ and $ match next to embedded \n
o Compile pattern only once. Used to optimize the search
s Treat string as single line when newline is embedded. Let . match newline
x Allows whitespace and comments whithin the regex
g Replace globally, i.e. find all occurrences
gc Alows continued search after failed /g match

 
-  e  -
1. 1 while $line =~ s/\t/' ' x (8 - $-[0] % 8)/e;  
2. $var=121; $var =~ s/2/2*4/e; # 181
3. $var=121; $c=4; $var =~ s/2/" $c*2 "/e; # 1 4*2 3
4. $var=121; $c=4; $var =~ s/2/" $c*2 "/ee; # 181

 
-  i  -
  $word="AbCdeF";  
1. print "$word\n" if $word =~ /abcd|ABCD/; #
2. print "$word\n" if $word =~ /abcd|ABCD/i; # AbCdeF

 
-  m  -
1. $str= "1. Smith\n\tJey \n\tAn\n2. Shevchenko\n\tTaras \n";  
  while ( $str =~ /(^\d.*$)/gm {  
    print "$1\n"; # 1. Smith
  } # 2. Shevchenko

 
-  x  -
  $a = "ABC"; $b = "WWW"; $c = "--($a)--($b)--";  
1. $c =~ s/  
    \( # left parenthese  
    (\w+) # capture any word  
    \) # right parenthese  
   / $1 /xg; # -- ABC -- WWW --

 
-  s  -
  $str = "12\n34";  
1. $str =~ s/./+/g; # ++
 # ++
2. $str =~ s/./+/sg; # +++++

 
-  g  -
  $name = "anatoliy";  
1. $name = s/(\w)/uc($1)/e; # Anatoliy
2. $name = s/(\w)/uc($1)/eg; # ANATOLIY

 
-  gc  -
  $_ = "123456abc7x"; $num = "\d\d\d"; $let = qr/[a-zA-Z]{3}/;
1. while (1) {
    if (m/($num)/g) { print "NUM: $1\n"; }
    elsif (m/($let)/g) { print "LET: $1\n"; }
    else { print "pos = " . pos() "\n" and last; }
  }
  # infinitive loop
 
2. while (1) {
    if (m/\G($num)/g) { print "NUM: $1\n"; }
    elsif (m/\G($let)/g) { print "LET: $1\n"; }
    else { print "pos = " . pos() "\n" and last; }
  }
  # NUM: 123
  # NUM: 456
  # Use of uninitialized value in concatenation ...
  # pos =
 
3. while (1) {
    if (m/\G($num)/gc) { print "NUM: $1\n"; }
    elsif (m/\G($let)/gc) { print "LET: $1\n"; }
    else { print "pos = " . pos() "\n" and last; }
  }
  # NUM: 123
  # NUM: 456
  # LET: abc
  # pos = 9