正则表达式替换函数包含太多文本

时间:2011-11-04 00:12:29

标签: python regex

我是一个蟒蛇新手。我的脚本(下面)包含一个名为的函数    用于转换的“fn_regex_raw_date_string”    像这样的“原始”日期字符串:2011年10月31日星期一晚上8:15    到这样的日期字符串:_2011-Oct-31_PM_8-15_

问题1:当“原始”日期字符串包含无关时     字符例如(xxxxxMon,2011年10月31日下午8:15 PMyyyyy),应该如何     我修改我的正则表达式例程以排除无关的字符?

  I was tempted to remove my comments from the script below to make it 
     simpler to read, but I thought it might be more helpful for me to leave 
     them in the script.

问题2:我怀疑我应该编写另一个函数     将“2011-Oct-31_PM_8-15_”中的“Oct”替换为“11”。但我不能     帮助想知道是否有某种方式来包含该功能     我的fn_regex_raw_date_string函数。

非常感谢任何帮助。

谢谢你,                                 Marceepoo

import sys
import re, pdb
#pdb.set_trace()

def fn_get_datestring_sysarg():
    this_scriptz_FULLName = sys.argv[0]
    try:
        date_string_raw = sys.argv[1]
    #except Exception, e:
    except Exception:
        date_string_raw_error = this_scriptz_FULLName + ':  sys.argv[1] error:  No command line argument supplied'
        print date_string_raw_error
    #returnval = this_scriptz_FULLName + '\n' + date_string_raw
    returnval = date_string_raw
    return returnval

def fn_regex_raw_date_string(date_string_raw):
    # Do re replacements
    # p:\Data\VB\Python_MarcsPrgs\Python_ItWorks\FixCodeFromLegislaturezCalifCode_MikezCode.py
    # see also (fnmatch) p:\Data\VB\Python_MarcsPrgs\Python_ItWorks\bookmarkPDFs.aab.py

    #srchstring = r"(.?+)(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(, )(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)( )([\d]{1,2})(, )([\d]{4})( at )([\d]{1,2})(\:)([\d]{1,2})( )(A|P)(M)(.?+)"
    srchstring = r"(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(, )(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)( )([\d]{1,2})(, )([\d]{4})( at )([\d]{1,2})(\:)([\d]{1,2})( )(A|P)(M)"

    srchstring = re.compile(srchstring)    
    replacement = r"_\7-\3-\5_\13M_\9-\11_"
    #replacement = r"_\8-\4-\6_\14M_\10-\12_"    
    regex_raw_date_string = srchstring.sub(replacement, date_string_raw)

    return regex_raw_date_string

    # Mon, Oct 31, 2011 at 8:15 PM  
if __name__ == '__main__':
    try:
        this_scriptz_FULLName = sys.argv[0]
        date_string_raw = fn_get_datestring_sysarg()
        date_string_mbh = fn_regex_raw_date_string(date_string_raw)
        print date_string_mbh
    except:
        print 'error occurred - fn_get_datestring_sysarg()'

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

此代码使用一个正则表达式,在匹配缩写的工作日之前替换字符串开头的所有内容,然后在匹配AM或PM之后将所有内容替换为字符串的结尾。

然后它调用datetime.strptime(date_str, date_format)来完成解析的艰苦工作并给我们一个datetime实例:

from datetime import datetime

import calendar
import re

# -------------------------------------

# _months = "|".join(calendar.month_abbr[1:])
_weekdays = "|".join(calendar.day_abbr)

_clean_regex = re.compile(r"""
    ^
    .*?
    (?=""" + _weekdays + """)
    |
    (?<=AM|PM)
    .*?
    $
""", re.X)

# -------------------------------------

def parseRawDateString(raw_date_str):
    try:
        date_str = _clean_regex.sub("", raw_date_str)
        return datetime.strptime(date_str, "%a, %b %d, %Y at %I:%M %p")

    except ValueError as ex:
        print("Error parsing date from '{}'!".format(raw_date_str))
        raise ex

# -------------------------------------

if __name__ == "__main__":
    from sys import argv

    s = argv[1] if len(argv) > 1 else "xxxxxMon, Oct 31, 2011 at 8:15 PMyyyyyy"

    print("Raw date:       '{}'".format(s))
    d = parseRawDateString(s)
    print("datetime object:")
    print(d)
    print("Formatted date: '{}'".format(d.strftime("%A, %d %B %Y @ %I:%M %p")))