in reply to Re^2: Generalising string in pattern
in thread Generalising string in pattern

Two ways:

  1. make a copy of the string and weed out the space characters
    my $string='i am using perl'; (my $str = $string) =~ s/\s+//g;
    then match $pattern against $str
  2. insert \s* after (or before) every character in the pattern.
    my $pattern = 'iamusingper'; $pattern =~ s/(.)/.\\s*$1/g;
    then match $pattern against $string

Update: contrary to the title, you apparently don't want to ignore spaces in the regular expression (that's what the /x modifier is for), but in the string you are matching against.

2009-11-14
Original title: 'ignoring spaces in the (was: Regular expressions) string'

Replies are listed 'Best First'.
Re^4: Generalising string in pattern
by keszler (Priest) on Nov 13, 2009 at 15:27 UTC
    An alternate to option 2, slightly faster:
    use strict; use Benchmark qw/cmpthese/; my $p = 'stringwithnospacesinit'; my ($a,$b); cmpthese( -5, { a => sub{ $a = $p; $a =~ s/(.)/$1\\s*/g; }, b => sub{ $b = $p; $b = join('\s*',split(//,$b)); }, } ); __END__ Rate a b a 62530/s -- -20% b 78403/s 25% --
    update - typo fix

      ... and add a leading and/or trailing \s* ;-)

      (update: only needed if the pattern is anchored)