If I'm following you correctly, you want 'h', 'he', 'hel', 'hell' and 'hello' all to match when the test is for 'hello'. You can use \b (
Using character classes) to anchor at the start (or end) of the word (it's a zero-width match), and then a series of ? (0 or 1 occurrences,
Matching repetitions) in a set of nested
Non capturing groupings with | (alternators,
Matching this or that). So for hello, you could use:
$line =~ /\bh(?:\b|e(?:\b|l(?:\b|l(?:\b|o))))/i;
Where I've added case-insensitivity for good measure. Note that this does not match 'howdy'. Given that you'll want to do this for multiple words, I imagine, you'll probably want to auto generate your regular expressions, using something like:
use strict;
use warnings;
while (<DATA>) {
my $regex = '\b' . substr $_,0,1;
foreach my $letter (split //, substr($_,1)) {
$regex .= '(?:\b|' . $letter;
}
$regex .= ')' x ((length)-1);
print $regex;
}
__DATA__
hello
Update: As usual, ikegami's code is better than mine. A rewritten autogenerator using his pattern (Update 2: including dependence on Perl version for regex):
use strict;
use warnings;
my $five10 = $] > 5.010 ? 1 : 0;
while (<DATA>) {
my $regex = '\b' . substr $_,0,1;
foreach my $letter (split //, substr($_,1)) {
$regex .= '(?:' . $letter;
}
$regex .= (')?' . '+' x $five10) x ((length)-1) . '\b';
print $regex;
}
__DATA__
hello
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.