返回

正则表达式教程:匹配带有中文字符的邮箱地址

正则表达式

一、正则解释

给定的正则表达式 /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/ 用于匹配邮箱地址,包括以下部分:

  • ^: 锚定行首。
  • [A-Za-z0-9\u4e00-\u9fa5]+: 匹配邮箱用户名部分,包括大小写字母、数字和中文汉字。
  • @: 匹配 "@" 符号。
  • [a-zA-Z0-9_-]+: 匹配邮箱域名部分,包括大小写字母、数字、下划线。
  • (\.[a-zA-Z0-9_-]+)+: 匹配域名后缀,可以包含多个点分隔的后缀。
  • $: 锚定行尾。

二、使用场景

该正则表达式广泛用于以下场景:

  • 验证用户输入的邮箱地址是否有效。
  • 从文本或数据库中提取邮箱地址。
  • 过滤带有中文字符的邮箱地址。

三、代码示例

JavaScript

const regex = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

const emails = ['90203918@qq.com', 'nbilly@126.com', '啦啦啦@126.com'];

emails.forEach(email => {
  if (regex.test(email)) {
    console.log(`${email} is a valid email address.`);
  } else {
    console.log(`${email} is not a valid email address.`);
  }
});

Java

import java.util.regex.Pattern;

public class EmailMatcher {

    public static void main(String[] args) {
        String regex = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+
import java.util.regex.Pattern;

public class EmailMatcher {

    public static void main(String[] args) {
        String regex = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";

        String[] emails = {"90203918@qq.com", "nbilly@126.com", "啦啦啦@126.com"};

        for (String email : emails) {
            if (Pattern.matches(regex, email)) {
                System.out.println(email + " is a valid email address.");
            } else {
                System.out.println(email + " is not a valid email address.");
            }
        }
    }
}
quot;
; String[] emails = {"90203918@qq.com", "nbilly@126.com", "啦啦啦@126.com"}; for (String email : emails) { if (Pattern.matches(regex, email)) { System.out.println(email + " is a valid email address."); } else { System.out.println(email + " is not a valid email address."); } } } }

PHP

<?php

$regex = '/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/';

$emails = array('90203918@qq.com', 'nbilly@126.com', '啦啦啦@126.com');

foreach ($emails as $email) {
    if (preg_match($regex, $email)) {
        echo "$email is a valid email address.<br>";
    } else {
        echo "$email is not a valid email address.<br>";
    }
}

Python

import re

regex = r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+
import re

regex = r'^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$'

emails = ['90203918@qq.com', 'nbilly@126.com', '啦啦啦@126.com']

for email in emails:
    if re.match(regex, email):
        print(f'{email} is a valid email address.')
    else:
        print(f'{email} is not a valid email address.')
#x27;
emails = ['90203918@qq.com', 'nbilly@126.com', '啦啦啦@126.com'] for email in emails: if re.match(regex, email): print(f'{email} is a valid email address.') else: print(f'{email} is not a valid email address.')