Jump to content

Archived

This topic is now archived and is closed to further replies.

oracle259

Optimizing Regex

Recommended Posts

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.

Share this post


Link to post
Share on other sites
{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 (?:).

Share this post


Link to post
Share on other sites
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. ;)

Share this post


Link to post
Share on other sites
[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]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.