Jump to content


Photo

Optimizing Regex


  • Please log in to reply
3 replies to this topic

#1 oracle259

oracle259
  • Members
  • PipPipPip
  • Advanced Member
  • 119 posts

Posted 06 July 2006 - 07:20 PM

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.



#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 06 July 2006 - 07:26 PM

{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}.

Update: Don't use () if you are not capturing anything; use (?:).
Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#3 oracle259

oracle259
  • Members
  • PipPipPip
  • Advanced Member
  • 119 posts

Posted 06 July 2006 - 08:21 PM

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. ;)


#4 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 06 July 2006 - 08:37 PM

<?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 />';
		}
?>

Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users