Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON PROBLEM: JUST PART 1C PLEASE lb. (5 pts) Write a regular expression patte

ID: 3596602 • Letter: P

Question

PYTHON PROBLEM: JUST PART 1C PLEASE

lb. (5 pts) Write a regular expression pattern that matches dates according to the following rules: date are written in three parts, in the order month, day, and optional year, where the parts are separated by the / character. The month is a one or two digit number in the range 1-12 (with no leading 0 allowed). The day is a one or two digit number in the range 1-31 (with a leading 0 allowed for one digit numbers). The year, if included, is a two digit number (each digit can be 0: generally, XX means 20XX) or a four digit number between 1900-2099. Put your answer in repatternlb.txt. Here are a few legal/illegal examples. Note there is no requirement that the month and day make sense: 2/30 and 9/31 are both syntactically legal, although neither makes semantic sense. Legal: Should Match :2/10, 2/10/06, 2/10/1906, 12/31/2015, 12/3, 12/03, 2/31, 9/4/13 Illegal: Should Not Match: 02/10, 13/10, 21/13, 12/ 13, 5, 5/, 5/1 lc. (2 pts) Write a regular expression patten that matches the same strings described in part 1b. But in addition for this pattern, ensure group 1 is the month; group 2 is the day; group 3 is the year. For example, if we execute m re.match (the-pattern, '10/13/2017') then m.groups() returns ('10', '13', '2017'). Likewise, if we execute m-re.match (the pattern, '10/13') then m.groups () retums ('10', '13', None): the None is because the optional year part of the pattern is missing: the online tool omits showing such a group. There should be no other numbered groups. Hint (?····) creates a parenthesized regular expression that is not numbered as a group. You can write one regular expression for both lb and 1c, or you can write a simpler one for lb (ignore groups) and then update it for lc by specifying the necessary groups. Put your answer in repatternlc.txt

Explanation / Answer

Hi,
here is the re pattern- '([0-9]*)/([0-9]*)/?(?:[0-9]*)', what this essentially does is, each () represents a group, here in our example, each group can have digits, and /? means a 0 or 1 '/' for the year part, please look at the usage of ?: which is called non capturing group , to make the year group optional
Here is the code you can use to test,

#!/usr/bin/python
import re
line = "12/10/2017"
matchObj = re.match( r'([0-9]*)/([0-9]*)/?(?:[0-9]*)', line)

if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
print "matchObj.group(3) : ", matchObj.group(3)
else:
print "No match!!"

Thumbs up if this was helpful, otherwise let me know in comments