From 8756bc4fe489edcb3f176428be4d21d682b57bcf Mon Sep 17 00:00:00 2001 From: kio <1> Date: Tue, 21 Dec 2021 10:31:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=954?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 04. regex_exception/xuhetong_04.py | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/04. regex_exception/xuhetong_04.py b/04. regex_exception/xuhetong_04.py index 0f54322..cc27708 100644 --- a/04. regex_exception/xuhetong_04.py +++ b/04. regex_exception/xuhetong_04.py @@ -6,15 +6,32 @@ def get_pattern_result_list(resource, pattern): return list(r) +def get_min_match(list_r, number): + min = 100000000 + min_item = None + for item in list_r: + if abs(int(item.group())-int(number)) < min: + min = abs(int(item[0])-int(number)) + min_item = item + return min_item + + + if __name__ == '__main__': with open('pi.txt', 'r') as f: pi = f.read() - pattern1 = "19910205" - r = get_pattern_result_list(pi, pattern1) + bir = "19910205" + # 1980 1984 1988 1992 1996 2000 闰年 + # 月份判断 反正很长写不出第二次 + pattern1 = "(((19[8-9][0-9]|2000)((01|03|05|07|08|10|12)(0[1-9]|[12][0-9]|3[01])|(04|06|09|11)(0[1-9]|[12][0-9]|30])|02(0[1-9]|1[0-9]|2[1-8])))|(1980|1984|1988|1992|2000)0229)" + r = get_pattern_result_list(pi, bir) if len(r) == 0: print(" no match") + r = get_pattern_result_list(pi, pattern1) + min_match = get_min_match(r, bir) + print(f"min match {min_match.group()} at {min_match.span()[0]} to {min_match.span()[1]}") else: - print(f"first match {r[0].group()} at {r[0].span()[0]} to {r[0].span()[1]}") + print(f" match {r[0].group()} at {r[0].span()[0]} to {r[0].span()[1]}") pattern2 = "(19[6-9][0-9]|20[0-1][1-9]|202[0-1])" r = get_pattern_result_list(pi, pattern2) -- Gitee