oracle259 Posted July 6, 2006 Share Posted July 6, 2006 I'm new to php and regex, as such i have been practicing. But its not only important that i learn how to simply write these expressions i also need to learn how to optimize then. I recently wrote this expression ^[A-Z]{1}([1]{4}|[2]{4}|[3]{4}|[5]{4}|[6]{4}|[7]{4}|[8]{4}|[9]{4})$Its meant to validate a 5 character alphanumeric PIN that starts with an uppercase letter and 4 digits (no zeros). Now i know it works but its not very pretty as u can see. My question is this how can i optimize it. Quote Link to comment Share on other sites More sharing options...
effigy Posted July 6, 2006 Share Posted July 6, 2006 {1} is assumed, therefore [A-Z] will do.The more |'s you use, the worse.To match 4 non-zero digits use [1-9]{4}.[b]Update:[/b] Don't use () if you are not capturing anything; use (?:). Quote Link to comment Share on other sites More sharing options...
oracle259 Posted July 6, 2006 Author Share Posted July 6, 2006 Sorry i should have explained further. The expression is meant to match patterns like A1111 or B2222 or E9999 only that is why i wanted to see if it could be done another way. ;) Quote Link to comment Share on other sites More sharing options...
effigy Posted July 6, 2006 Share Posted July 6, 2006 [code]<?php $tests = array( 'A1111', 'B2222', 'C3333', 'A1234', 'B2223', 'C3332', ); foreach ($tests as $test) { echo "<b>Testing '$test':</b>"; echo preg_match('/^[A-Z]([1-9])\1{3}$/', $test) ? 'Has 4 identical digits' : 'Does not have 4 identical digits' ; echo '<br />'; }?>[/code] Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.