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

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re^3: Generalising string in pattern
by shmem (Chancellor) on Nov 13, 2009 at 15:04 UTC

    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'

      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)

Re^3: Generalising string in pattern
by toolic (Bishop) on Nov 13, 2009 at 15:03 UTC
    Two ways to do it:

    1. Change your pattern as follows:

    $pattern = qr/i\s*am\s*using\s*per/;

    2. Make a copy of your string with the spaces removed.

Re^3: Generalising string in pattern
by ww (Archbishop) on Nov 13, 2009 at 14:25 UTC
    Again, consult perldoc perle. Using a character class containing only a space is one of many ways to do this.
    my $pattern = qr(i[ ]*am[ ]*using[ ]*per);

    And, when you post code, you'll help yourself by first checking that code by:

    use strict; use warnings

    and then perl -c scriptname.

    The apparent failure to do the above; the apparent failure to take several pieces of advice in previous replies; and the missing semi-colons suggest that you don't care so much about learning from the wisdom of the Monks as about using them to write your code.

      I do not want generalise $pattern.I want my search of the $pattern which is without spaces ignore the spaces in the $string

        If you want to ignore whitespace, you will have to create a new pattern.