I'm coding in PHP, but this is a generic regular expression question. I'm trying to interrogate a character string of any length, to see if it contains the letter c followed by a number of up to 3 digits and a period (.) but at the same time rejecting other more complex strings. So .. You are a clown99. - false You are a clown c99. - true You will love c3po. - false You will love c3.po - true Is there a regular expression syntax to check for this ?
$testCases = array("You are a clown99.", "You are a clown c99.","You will love c3po.","You will love c3.po"); $pattern = '/c(\d){1,3}\./'; foreach ($testCases as $case) { if(preg_match($pattern, $case) == TRUE) { print "Match on string: $case <br />"; } } Code (markup): explanation: c // matches the c character (\d){1,3} // matches a digit (/d) that appears 1 to 3 times {1,3} \. // matches the period If you wanted to match an upper or lower case C, use $pattern = '/[C|c](\d){1,3}\./'; Code (markup):
Thanks for that I found this site after I posted: http://www.regular-expressions.info/javascriptexample.html and came up with this: [c][0-9]{1,3}\. but yours looks a lot better
Your code is identical to mine in functionality. The \d I used performs the same search as [0-9], and putting the c inside square brackets is fine as well. Regular expressions are very useful, check out this website if you're looking for a good resource. http://krijnhoetmer.nl/stuff/regex/cheat-sheet/ Also, that javascript regex tester is a very nice find.