实验题目:正则表达式
- 实验目的及意义
设计并实现一个正则表达式检测强密码算法。通过该实验使学生综合掌握并灵活使用正则表达式。
- 实验相关知识点及要求
- String, List, Regular Expression
- 编写一个函数,用于判定给出的字符串序列符合强密码要求:至少8个字符,包含大小写字母和至少一个数字。
- 请给出匹配如下模式的正则表达式:
‘42’,‘1,234’,‘6,368,745’,但是不包含: `12,34,567’, ‘1234’
- 请给出匹配电子邮箱地址的正则表达式。
- 实验步骤
- 实验步骤框图
第二题(编写一个函数,用于判定给出的字符串序列符合强密码要求:至少8个字符,包含大小写字母和至少一个数字)实验步骤框图:
第三题(请给出匹配如下模式的正则表达式:‘42’,‘1,234’,‘6,368,745’,但是不包含: `12,34,567’, ‘1234’)实验步骤框图:
第四题(请给出匹配电子邮箱地址的正则表达式)实验步骤框图:
-
- 实验各步骤具体内容
第二题(编写一个函数,用于判定给出的字符串序列符合强密码要求:至少8个字符,包含大小写字母和至少一个数字)实验代码与结果截图:
def password_check(passwd):
val = True
# check the length
if len(passwd) < 8:
print('length should be at > 8')
val = False
else:
print('length is than 8 ')
# check the number
if not any(char.isdigit() for char in passwd):
print('Password should have at least one numeral')
val = False
else:
print('password have least one numeral')
# check the uppercase
if not any(char.isupper() for char in passwd):
print('Password should have at least one uppercase letter')
val = False
else:
print('Password have at least one uppercase letter')
# check the lowercase
if not any(char.islower() for char in passwd):
print('Password should have at least one lowercase letter')
val = False
else:
print('Password have least one lowercase letter')
if val:
return val
def main():
if password_check(password):
print('Password is valid')
else:
print("Invalid Password !!")
# Driver Code
if __name__ == '__main__':
password = input('Enter your password: ')
main()
第三题(请给出匹配如下模式的正则表达式:‘42’,‘1,234’,‘6,368,745’,但是不包含: `12,34,567’, ‘1234’)实验代码与结果截图:
import re
def contains_numbers(text):
if re.search(r"(^|\D)(42|1,234|6,368,745)(\D|$)", text):
if not re.search(r"(^|\D)(12,34,567|1234)(\D|$)", text):
return True
return False
text1 = input()
print(contains_numbers(text1))
第四题(请给出匹配电子邮箱地址的正则表达式)实验代码与结果截图:
import re
pat = r'^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$'
email_address = '20101110227@ncut.edu.com'
matched_address = re.match(pat, email_address)
print(matched_address.group())
四、实验结论