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

Regex - repeating pattern 2

Status
Not open for further replies.

Borvik

Programmer
Jan 2, 2002
1,392
0
0
US
I'm sure the answer is a fairly simple regex pattern - but I seem to have difficulty with all the nuances of regex.

I'm looking for a regex to validate a repeating pattern of characters. The pattern is AAA-AAA where is any alphanumeric character ([A-Z0-9] - I'll be using strtoupper before the regex). This pattern could repeat any number of times from 1 (AAA) to infinity, but always in 3 alphanumeric character groups separated by a dash(-).

Incomplete patterns should not match (AAA-) or (AAA-AA).

Here is the regex I've come up with so far: /^([A-Z0-9]{3,}-?)*?$/

It appears to work so far, but incomplete patterns that look like (AAA-) in other words a valid set of alphanumeric characters ending with a dash still get a valid result.

Any regex gurus out there that can help with this?

Thanks.
 
there's a regex way to do this with a lookahead (I think). but the better way to do it would be with a user function

Code:
function testString($string){
 $array = explode ('-', $string);
 foreach ($array as $s) {
    if (!preg_match('/^[a-z0-9]{3,3}$/i', $s)) return false;
 }
  return true;
}
 
and i think that there is a way to do this without lookaheads too

Code:
$pattern = '/^[a-z0-9]{3,3}((-[a-z0-9]{3,3})+$|$)/ims';

which says, basically, that
1. match alpha 3 times and only three times
2. then match either the end of the string OR
3. match a repeating string (1 or more times) of a dash followed by three alpha numeric characters followed by either a repeat of the same OR the end of the string.


 
The 'i' REGEX modifier will render the search case-insensitive.
 
exactly. so you don't need to worry about strtoupper()
 
Duh - case-insensitive modifier. I'm not sure why I didn't see that - it was near the end of the day and my brain was shutting down is the only thing I can come up with.

Thanks guys for the tips guys.

I remembered something about lookaheads this morning and did some digging on that (before I had checked back here) and came up with the following (which I'm adding those modifiers to - now that you mention them):
Code:
$pattern = '/^([A-Z0-9]{3,3})(-(?=[A-Z0-9]{3,3})[A-Z0-9]{3,3})*$/ims'

You think that function with the explode and loop would be better jpadie? Any particular reason that would be better than the regex? Would that have better performance or something?
 
actually i think that my second post of 17h44 will have the best performance. it does not use lookaheads, which will speed up the regex considerably.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top