<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def in_period(period, dt=None):
 """ Determines if a datetime is within a certain time period. If the time is omitted the current time will be used. in_period return True is the datetime is within the time period, False if not. If the expression is malformed a TimePeriod.InvalidFormat exception will be raised. (Note that this differs from Time::Period, which returns -1 if the expression is invalid). The format for the time period is like Perl's Time::Period module, which is documented in some detail here: http://search.cpan.org/~pryan/Period-1.20/Period.pm Here's the quick and dirty version. Each period is composed of one or more sub-period seperated by a comma. A datetime must match at least one of the sub periods to be considered in that time period. Each sub-period is composed of one or more tests, like so: scale {value} scale {a-b} scale {a b c} The datetime must pass each test for a sub-period for the sub-period to be considered true. For example: Match Mondays wd {mon} Match Monday mornings wd {mon} hr {9-16} Match Monday morning or Friday afternoon wd {mon} hr {0-12}, wd {fri} hr {0-12} Valid scales are: year month week yday mday wday hour minute second Those can be substituted with their corresponding code: yd mo wk yd md wd hr min sec """


    if dt is None:
        dt = datetime.now()

    # transform whatever crazy format we're given and turn it into
    # something like this:
    #
    # md{1}|hr{midnight-noon},md{2}|hr{noon-midnight}
    period = re.sub(r"^\s*|\s*$", '', period)
    period = re.sub(r"\s*(?={|$)", '', period)
    period = re.sub(r",\s*", ',', period)
    period = re.sub(r"\s*-\s*", '-', period)
    period = re.sub(r"{\s*", '{', period)
    period = re.sub(r"\s*}\s*", '}', period)
    period = re.sub(r"}(?=[^,])", '}|', period)
    period = period.lower()

    if period == '':
        return True

    sub_periods = re.split(',', period)

    # go through each sub-period until one matches (OR logic)
    for sp in sub_periods:
        if _is_in_sub_period(sp, dt):
            return True

    return False