Regular Expressions Nils Murrugarra
Exercise 1 Write a regular expression that will match a time/clock hh:mm:ss pattern. Examples: "00:00:15" is valid "0:56:25" is not valid “11:15:09" is valid "15:96:22" is not valid 2 Solution: /([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/ Solving … Solution2: /([01]\d|2[0-3]):([0-5]\d):([0-5]\d)/
Exercise 1 - Solution // time echo "Example Time "; $subject="00:00:15 0:56:25 95:00:25 11:15:09 15:96:22 20:15:10 "; $pattern = "/([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/"; if (preg_match_all($pattern, $subject, $result, PREG_OFFSET_CAPTURE)): echo "$pattern was found: \n"; print_r($result); nl(); endif; 3
Exercise 1 - Solution 4 TimeAccept? 00:00:15Yes 0:56:25No 95:00:25No 11:15:09Yes 15:96:22No 20:15:10Yes Run Program … ClickClick
Exercise 1 - Report/Answers Array ( [0] => Array ( [0] => Array ( [0] => 00:00:15 [1] => 0 ) [1] => Array ( [0] => 11:15:09 [1] => 26 ) [2] => Array ( [0] => 20:15:10 [1] => 44 ) ) [1] => Array ( [0] => Array ( [0] => 00 [1] => 0 ) [1] => Array ( [0] => 11 [1] => 26 ) [2] => Array ( [0] => 20 [1] => 44 ) ) [2] => Array ( [0] => Array ( [0] => 00 [1] => 3 ) [1] => Array ( [0] => 15 [1] => 29 ) [2] => Array ( [0] => 15 [1] => 47 ) ) [3] => Array ( [0] => Array ( [0] => 15 [1] => 6 ) [1] => Array ( [0] => 09 [1] => 32 ) [2] => Array ( [0] => 10 [1] => 50 ) ) 5
Exercise 2 Write a regular expression that will match a zip code. The zip pattern may be like "16059" or the expanded form of " ". If there is a dash after the 5 digits then there must follow exactly 4 digits. Examples: "15221-abcd " is not valid "12345 " is valid “ " is valid “ “ is not valid 6 Solution: /\d{5}(-\d{4})?/ Solving …
Exercise 2 - Solution //zip code echo "Example Zip-code "; $subject="15221-abcd "; $pattern = "/\d{5}(-\d{4})?/"; if (preg_match_all($pattern, $subject, $result, PREG_OFFSET_CAPTURE)): echo "$pattern was found: \n"; print_r($result); nl(); endif; 7
Exercise 2 - Solution 8 Zip CodeAccept? abcdNo 12345Yes No Yes 1235No 54263Yes Yes Run Program … ClickClick
Exercise 2 – Report/Answers 9 Array ( [0] => Array ( [0] => Array ( [0] => [1] => 0 ) [1] => Array ( [0] => [1] => 11 ) [2] => Array ( [0] => [1] => 17 ) [3] => Array ( [0] => [1] => 27 ) [4] => Array ( [0] => [1] => 43 ) [5] => Array ( [0] => [1] => 49 ) ) [1] => Array ( [0] => [1] => [2] => [3] => Array ( [0] => [1] => 32 ) [4] => [5] => Array ( [0] => [1] => 54 ) )
10 Questions