How to code this regular expression ...

Discussion in 'Programming' started by fulltilt, Jan 29, 2009.

  1. #1
    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 ?
     
    fulltilt, Jan 29, 2009 IP
  2. w0tan

    w0tan Peon

    Messages:
    77
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    $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):
     
    w0tan, Jan 29, 2009 IP
  3. fulltilt

    fulltilt Peon

    Messages:
    128
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    fulltilt, Jan 29, 2009 IP
  4. w0tan

    w0tan Peon

    Messages:
    77
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #4
    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.
     
    w0tan, Jan 29, 2009 IP