in reply to Matching a truncated word

Clarification: It should match the truncated piece of the last word, but the string being searched contains stuff before that. E.g.
$text= "This sentence ends in foob"; # truncated from "...foobar" $text =~ /foobar$/; $text =~ /fooba$/; $text =~ /foob$/; ... etc. ...

Replies are listed 'Best First'.
Re^2: Matching a truncated word
by tadman (Prior) on Aug 01, 2001 at 00:28 UTC
    Hopefully this isn't too obfuscated. I've tried to restrain myself here. The trunc_match function creates a regular expression for any given input string, and should handle wierd stuff to by virtue of the qr() operator.
    sub trunc_match { my ($what) = @_; my @bits; for (1..length $what) { push (@bits,$what); chop $what; } return '('.join ('|', map { quotemeta($_) } @bits).')$'; } my $rx = trunc_match ("foobar"); $_ = "This sentence ends in foob"; if (/$rx/) { print "Truncated, ends in '$1'\n"; }
    The format of the regex is something like:
    (foobar|fooba|foob|foo|fo|f)$
    So you get whatever you're looking for in $1, or the returned array if you're brave enough to use /g.

    Update:
    For some reason, I had confused qr with quotemeta, and so I am updating the code here to be more sensible in that regard. Thanks, once again, Hofmator.
      That's an interesting use of qr// to escape out the individual parts, instead of using logic involving \Q..\E. I like the idea, since it avoids the confusion of escape chars in strings vs. in regex, and multiple levels of escaping. I'll be sure to remember that.