Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression-matching n character of a string

Status
Not open for further replies.

broloc

Programmer
Jun 10, 2002
27
JP
how do i match n character of a string using regular expression?..for example i got a string charmed,i want at least 4 character matched with exact position,so that if i keyed in cracked,the expression will return true.any advice will be much appriciated.thanx.
 
$word = "charmed";
$word_2 = "cracked";

for($x=0;$x <= length($word); $x++){
$matchCount++
if(substr($word,$x,1) eq substr($word_2,$x,1));
}

print $matchCount, &quot; character location matches\n&quot;;

 
maybe i didn't put the question right.i don't want to determine the number of character matched.now..i have a string,$mystring=charmed.and user will be ask to enter an input(a string of course),$input..and my program will determined if $input matched with $mystring.if it matched,my program will return true.$input will be consider matched if at least 4 or all of the character in $input matched with $mystring..for example if user key in cracked,then my program will return true...hope this is clear enough.
 
Broloc,

Coderifous' routine will work for you if you wrap it into a sub.

sub MatchCount($$){
my ($word, $word_2) =@_;

my $x, $matchCount;

for($x=0;$x <= length($word); $x++){
$matchCount++
if(substr($word,$x,1) eq substr($word_2,$x,1));
}

return $matchCount;

}

Then, in your script, you can say:

if (MatchCount('charmed','cracked') >= 4){
print &quot;Matched\n&quot;;
} Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top