| Refresh | Home EGTry.com

extract multiple mixed patterns -perl lexer


match flag

flag meaning
\g each match start from the previous position left which can be set or retrieved by pos()
\G use together with \g, scan from left to right, don't skip unmatched character
\c use together with \g, if match fails, do not reset pos()

use strict;

my $text=q|my name is $name. I have ${config.maximum}. The end|;

my @words=extract($text);

print join(",", @words), "\n";

sub  extract {
  my $line=shift;
  my @tokens;
  while(1) {
    if ($line =~ /\G\$(\w+)/gc) {
      print "\$var: $&, $1\n";
      push @tokens, $1;
      next;
    } 
    if ($line =~ /\G\$\{([^}]+)\}/gc) {
      print "\${namespace.var}: $&, $1\n";
      push @tokens, $1;
      next;
    } 
    if ($line =~ /\G[^\$]+/gc) {
      print "other: $&\n"; 
      next;
    } 
    last;
  }
  print "\n";
  return @tokens;
}



output:

other: my name is 
$var: $name, name
other: . I have 
${namespace.var}: ${config.maximum}, config.maximum
other: . The end

name,config.maximum