How to validate phone number using regular expression in golang

WBOY
Release: 2023-06-24 20:38:21
Original
1850 people have browsed it

In Golang, using regular expressions to verify phone numbers is a very simple and convenient method. In Golang, using regular expressions requires using the regular expression package. This article will introduce how to verify phone numbers using the regular expression package in Golang.

  1. Import the regular expression package

In Golang, using regular expressions requires importing the regular expression package. In Golang, the name of the regular expression package is regexp. Import the regular expression package via:

import "regexp"

  1. Validate phone numbers using regular expressions

In Golang, use regular expressions Expressions can validate phone numbers. The following is a sample regular expression:

pattern := ^1[3456789]d{9}$

where ^ represents the beginning of the string and $ represents the character At the end of the string, [] represents a character set, d represents any number, and {9} represents 9 occurrences. Therefore, this regular expression represents a string starting with 1, followed by any number from 3, 4, 5, 6, 7, 8, 9, and then any 9 numbers.

The following is a sample program that uses regular expressions to verify whether the string phone is a valid Chinese mobile phone number:

package main

import (

"fmt"
"regexp"
Copy after login

)

func main() {

// 手机号码
phone := "13912345678"

// 编译正则表达式
pattern := `^1[3456789]d{9}$`
reg := regexp.MustCompile(pattern)

// 验证手机号码
if reg.MatchString(phone) {
    fmt.Println("Valid phone number")
} else {
    fmt.Println("Invalid phone number")
}
Copy after login

}

In the above example program, use the MatchString() function to determine whether the phone can match the regular expression pattern.

  1. Conclusion

Using regular expressions to verify phone numbers is a very common technique. In Golang, it is very convenient to use the regular expression package. This article introduces how to use regular expressions to verify phone numbers in Golang. I hope it will be helpful to readers.

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

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