Discuss / Python / 练习

练习

Topic source

AL

#1 Created at ... [Delete] [Delete and Lock User]

练习1:

def is_valid_email(addr):
   rule = re.compile( r'^([a-zA-Z\.]+)@([a-zA-Z0-9]+).com$' )
   """
   re.compile() 将正则表达式编译成一个Pattern规则对象,单独使用compile 没有意义,
   他生成的是一个规则,需要match ,search 等去使用这个规则
   
   r':防止字符转义,\n就是\n,而不是换行
   ^:行开头,$:行结尾。有没有不影响编译通过,但加上更精准
   [a-zA-Z\.]+ :匹配字母或【底部点】,且至少一个字符
   """
   return rule.match(addr)

练习2:

def name_of_email(addr):
    m =re.match(r'\<?([\w\s]+)\>?[\w\s]*@voyager.org',addr)
    """
    \<:选择左尖括号"<"
    \<?:“?”表示0个或1个
    \w:字数或数字,\s:空格
    ([\w\s]+) 表示匹配一个或多个单词字符或空格,并将其保存在一个分组中,以便之后可以使用该分组中的内容。
    [\w\s]*:“*”表示任意个,包括0个。短式指代第一个assert的tom或第二个assert的不存在
    """
    return m.group(1)
    # group(0)是与【整个】正则表达式相匹配的字符串,group(1)、group(2)……表示第1、2、……个子串

  • 1

Reply