|
199鱼币
本帖最后由 不二如是 于 2019-9-17 09:32 编辑
编写一个函数验证电子邮件地址:
@之前
- 以字母或数字开头
- 允许使用字母(大小写都可以)、数字、'.'、'-'、'\'
- 3 <= 长度 <= 20
@之后
- 至少两个子域
例如:@xxx.com(√) ,@com(x)
- 允许字母和数字
- 域名后缀应包含 2-8 个字符
为方便验证,提供 Python 和网页代码(只需替换 16 行正则内容即可)。
Python:
- import re
- c = re.compile(r'^[a-zA-Z0-9]+(\.[a-zA-Z0-9_-]+){2,19}@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+){1,7})
- email = raw_input('type an email:')
- s = c.search(email)
- if s:
- # print(s.group())
- print(email)
- else:
- print 'False'
复制代码
Web:
- <!doctype html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>验证</title>
- </head>
- <body>
- <form action="">
- 输入:<input type="text" name="tstEmail" id="mazey" placeholder="请输入邮箱">
- <input type="button" value="验证" onclick="check();">
- </form>
- <script>
- function check(){
- var reg = new RegExp("^[a-zA-Z0-9]+(\\.[a-zA-Z0-9_-]+){2,19}@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+){1,7}+$"); //正则表达式
- var obj = document.getElementById("tstEmail"); //要验证的对象
- if(obj.value === ""){ //输入不能为空
- alert("输入不能为空!");
- return false;
- }else if(!reg.test(obj.value)){ //正则验证不通过,格式不对
- alert("验证不通过!");
- return false;
- }else{
- alert("通过!");
- return true;
- }
- }
- </script>
- </body>
- </html>
复制代码
本帖最后由 XiaoPaiShen 于 2019-9-21 01:30 编辑
我来:
- import re
- c = re.compile(r'^([a-zA-Z0-9]{1}[\\a-zA-Z0-9.\-]{2,19})@([a-zA-Z0-9]+[a-zA-Z0-9.]+[.]{1}[a-zA-Z0-9]{2,8}))
- email = input('type an email:')
- s = c.search(email)
- if s:
- # print(s.group())
- print(email)
- else:
- print('False')
复制代码
c = re.compile(r'^([a-zA-Z0-9]{1}[\\a-zA-Z0-9.\-]{2,19})@([a-zA-Z0-9]+[a-zA-Z0-9.]+[.]{1}[a-zA-Z0-9]{2,8})$')
在代码块中,正则表达式的最后$'给去掉了
|
最佳答案
查看完整内容
我来:
c = re.compile(r'^([a-zA-Z0-9]{1}[\\a-zA-Z0-9.\-]{2,19})@([a-zA-Z0-9]+[a-zA-Z0-9.]+[.]{1}[a-zA-Z0-9]{2,8})$')
在代码块中,正则表达式的最后$'给去掉了
|