Home > Article > Backend Development > Go language regular expression skills: How to match the operator of a mobile phone number
Go language regular expression skills: How to match the operator of a mobile phone number
Introduction:
Regular expression is a powerful string matching tool that can be used to find matches in text that match a certain A pattern string. In the Go language, the regexp
package in the standard library provides support for regular expressions. This article will introduce how to use regular expressions to match the operator of a mobile phone number, helping readers better use regular expressions to process mobile phone numbers.
regexp.MustCompile
function to compile and return a *regexp.Regexp
instance. The following is a sample code: import "regexp" func main() { // 手机号码运营商正则表达式 regex := regexp.MustCompile(`^1(3[4-9]|4[7]|5[0-27-9]|7[678]|8[2-478])d{8}$`) // 进行手机号码运营商匹配 phoneNumber := "13456789012" if regex.MatchString(phoneNumber) { println("匹配成功") } else { println("匹配失败") } }
In the above code, the regular expression ^1(3[4-9]|4[7]|5[0-27-9 ]|7[678]|8[2-478])d{8}$
is used to match mainland China mobile phone numbers. This regular expression can match mobile phone numbers starting with 1
, followed by 3, 4, 5, 7 or 8, and then 8 digits. If the match is successful, "Match Success" is output, otherwise "Match Failed" is output.
import ( "fmt" "regexp" ) func main() { // 手机号码运营商正则表达式 regex := regexp.MustCompile(`^1((3[4-9])|(4[7])|(5[0-27-9])|(7[678])|(8[2-478]))d{8}$`) // 进行手机号码运营商匹配 phoneNumber := "13456789012" if regex.MatchString(phoneNumber) { // 提取运营商信息 result := regex.FindStringSubmatch(phoneNumber) if len(result) > 1 { fmt.Printf("运营商:%s ", getCarrier(result[1])) } } else { println("匹配失败") } } // 根据运营商编码获取运营商名称 func getCarrier(code string) string { switch code { case "34", "35", "36", "37", "38", "39": return "中国移动" case "47": return "中国移动(物联网号码)" case "50", "51", "52", "57", "58": return "中国联通" case "70", "71", "72": return "中国联通(物联网号码)" case "82", "83", "84", "85", "86", "87", "88", "89", "80": return "中国电信" case "74": return "中国电信(物联网号码)" } return "未知运营商" }
In the above code, we use the subexpression (3[4-9])|(4[7])|(5[0-27-9]) |(7[678])|(8[2-478])
to match the carrier code, and use the regex.FindStringSubmatch
function to extract the carrier code as a parameter to call getCarrier
Function, get the operator name and print it.
The above is the content of this article, I hope it will be helpful to readers.
The above is the detailed content of Go language regular expression skills: How to match the operator of a mobile phone number. For more information, please follow other related articles on the PHP Chinese website!