http://www.perlmonks.org?node_id=638734

atemon has asked for the wisdom of the Perl Monks concerning the following question:

There are 2 strigs, say

$x="My name is VC"; $y="myname";
I want to search for $y in $x regardless of the spaces and case and retrieve the matched string in $x. In $x, the extra character comes can be space (only) and it can come any number of times like "My Na me"

We can match by making a temp string and removing space and match. Then I cant get the matching string :(

Thanks in advance.

--VC



There are three sides to any argument.....
your side, my side and the right side.

Replies are listed 'Best First'.
Re: Regx: match without regarding space and case
by Sidhekin (Priest) on Sep 13, 2007 at 06:06 UTC

    This works for me:

    my $x="My name is VC"; my $y="myname"; my $r = do { local $" = ' *'; my @r = split //, $y; qr/@r/i }; if ($x =~ /($r)/) { printf "Matched from %d to %d: '%s'\n", $-[0], $+[0], $1; }

    Prints:

    Matched from 0 to 7: 'My name'

    print "Just another Perl ${\(trickster and hacker)},"
    The Sidhekin proves Sidhe did it!

Re: Regx: match without regarding space and case
by GrandFather (Saint) on Sep 13, 2007 at 07:14 UTC

    Use the translate operator (see tr/SEARCHLIST/REPLACEMENTLIST/cds) to delete the spaces, then use a case insensitive match. The code below captures the matched string to retain the original case, but doesn't attempt to figure out the "spacey" version of the match:

    use strict; use warnings; my $x="My name is VC"; my $y="myname"; $x =~ tr/ //d; print "Matched: >$1<\n" if $x =~ /(\Q$y\E)/i;

    Prints:

    Matched: >Myname<

    DWIM is Perl's answer to Gödel

      but doesn't attempt to figure out the "spacey" version of the match:

      But getting the spacey version was what the OP was asking for, wasn't it?


      s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
      +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Regx: match without regarding space and case
by Skeeve (Parson) on Sep 13, 2007 at 08:44 UTC
    A variation of Sidhekin's solution:
    #!/usr/bin/perl my $x="My name is VC"; my $y="myname"; my $r; ($r=$y)=~ s/(\S)(?!$)/$1 */g; $r= qr/($r)/i; if ($x =~ $r) { printf "Matched from %d to %d: '%s'\n", $-[0], $+[0], $1; }

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
Re: Regx: match without regarding space and case
by narainhere (Monk) on Sep 13, 2007 at 16:38 UTC
    Adding up to it, is there a way to differentiate the space characters \s and \t (That means a single space like ' ' and a tab like (' ') this.

    The world is so big for any individual to conquer

      \s is not a space, but is any whitespace, including tab and newline. You differentiate " " from "\t" just like this.

      Caution: Contents may have been coded under pressure.