How to validate email address in Golang using regular expression?

WBOY
Release: 2024-05-31 13:04:57
Original
259 people have browsed it

要使用正则表达式在 Golang 中验证电子邮件地址,请执行以下步骤:使用 regexp.MustCompile 创建一个正则表达式模式,匹配有效的电子邮件地址格式。使用 MatchString 函数检查字符串是否与模式匹配。该模式涵盖了大多数有效的电子邮件地址格式,包括:局部用户名可以包含字母、数字和特殊字符:!.#$%&'*+/=?^_{|}~-`域名至少包含一个字母,后面可以跟字母、数字或连字符顶级域名(TLD)不能超过 63 个字符长

如何使用正则表达式在 Golang 中验证电子邮件地址?

如何使用正则表达式在 Golang 中验证电子邮件地址

正则表达式是一种用于匹配字符串模式的强大工具。在 Golang 中,我们可以使用 regexp 包提供的 MustCompile 函数来创建正则表达式,并使用 MatchString 函数来检查字符串是否与模式匹配。

要验证电子邮件地址,我们可以使用以下正则表达式模式:

emailRegex := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")
Copy after login

这个模式涵盖了大多数有效的电子邮件地址格式,包括:

  • 局部用户名可以包含字母、数字和以下特殊字符:!.#$%&'*+/=?^_{|}~-`
  • 域名至少包含一个字母,后面可以跟字母、数字或连字符
  • 顶级域名(TLD)不能超过 63 个字符长

实战案例

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // 创建正则表达式
    emailRegex := regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$")

    // 检查一些电子邮件地址
    addresses := []string{"john@example.com", "mary@example.net", "bob@example.org", "invalid@example"}
    for _, address := range addresses {
        if emailRegex.MatchString(address) {
            fmt.Printf("%s 是一个有效的电子邮件地址\n", address)
        } else {
            fmt.Printf("%s 不是一个有效的电子邮件地址\n", address)
        }
    }
}
Copy after login

运行此程序将输出:

john@example.com 是一个有效的电子邮件地址
mary@example.net 是一个有效的电子邮件地址
bob@example.org 是一个有效的电子邮件地址
invalid@example 不是一个有效的电子邮件地址
Copy after login

The above is the detailed content of How to validate email address in Golang using regular expression?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!