george Posted January 27, 2012 Share Posted January 27, 2012 I have a string pattern I want to match with preg_match,a match starts with 99 or 88, thenfive digits from 00000-99999, followed byto upper case letters. the regular expression I came up with is if (preg_match("/^[99|88]([0-9]{5})([A-Z]{2}$)/", $subject1)) { echo "A match was found.<br />";} else { echo "A match was not found.<br />";} and the strings I chose to test are:/* THREE TRUE */$subject1 = "9912345AB";$subject2 = "8888412CC";$subject3 = "8845459ZA";/* THREE FALSE */$subject4 = "7712345AB";$subject5 = "9912345ab";$subject6 = "99123AB";What am I missing?As always, help very much appreciated. Link to comment Share on other sites More sharing options...
birbal Posted January 27, 2012 Share Posted January 27, 2012 It looks ok. There are free regex checker proogram. you may want to download one of them Link to comment Share on other sites More sharing options...
Ingolme Posted January 27, 2012 Share Posted January 27, 2012 Your problem here is using square brackets instead of parenthesis: [99|88] instead of (99|88) Link to comment Share on other sites More sharing options...
george Posted January 27, 2012 Author Share Posted January 27, 2012 Your problem here is using square brackets instead of parenthesis: [99|88] instead of (99|88) Tried that, did not work. Then I found on Wikipedia that [...] Denotes a set of possible character matches. 99 or 88 in my case.Where as ( ) Groups a series of pattern elements to a single element. Plus that section of the regular expression works just fine.Thanks for looking though. Link to comment Share on other sites More sharing options...
justsomeguy Posted January 27, 2012 Share Posted January 27, 2012 That part doesn't work fine, square brackets denote a character class. You are telling it to look for the digit 9, or the digit 9, or the character "|", or the digit 8, or the digit 8. That's what square brackets means, it is a class of characters where it matches one character inside the class. Check this page: http://www.quanetic.com/Regex In the pattern box, enter this: /^[99|88]$/ In the haystack box, notice that when you enter "99" or "88" it does not match. It will match if you enter "9", "|", or "8", because that's what you're telling it to look for. If you replace the square brackets with parentheses it matches either "99" or "88". Try this pattern: /^(99|88)[0-9]{5}[A-Z]{2}$/ When in doubt, use a tool to test the parts of your pattern. Don't assume you know what anything is doing if you haven't tested each part. Link to comment Share on other sites More sharing options...
george Posted January 27, 2012 Author Share Posted January 27, 2012 I stand corrected and my problem is solved. Thanks again everyone. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.