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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

restricting the number of instances of a character 1

Status
Not open for further replies.

fluid11

IS-IT--Management
Jan 22, 2002
1,627
US
Newbie Perl question...

If you wanted to match for 2-5 x's, followed by a z, this pattern match should work...

/x{3,5}z/

If I enter less than 3 x's, it returns false as it should, but if I enter more than 5 x's, it returns true, which is wrong.

I'm using a script that tests different regular expressions...


print "Enter a string: ";
chomp($string = <STDIN>);
print &quot;Enter a pattern: &quot;;
chomp($pattern = <STDIN>);

if ($string =~ /$pattern/) { print &quot;True\n&quot;; }
else { print &quot;False\n&quot;; }



Also, the ? character is supposed to match zero or one instance of the character before it. If I enter ddd as the string, and /d?/ as the pattern, it still returns true. I thought that it would only return true if there were either zero or one instance of the letter d


Thanks,

ChrisP
RHCE, LPIC-1, CCNA, CNE, MCSE, +10 others
 
In your first example, xxxxxxxxxxz would match because it does contain 5 x's followed by a z - xxxxx(xxxxxz)

/^x{2,5}z$/ should match what you want. ^ and $ anchor the match to the beginning and end of the string.

/d?/ will always return true.. any string could contain either zero d's or one d.
 
I see, I need to anchor the pattern to search for that specific string.

Thanks,

ChrisP
RHCE, LPIC-1, CCNA, CNE, MCSE, +10 others
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top