SoFunction
Updated on 2025-03-01

Example of Golang regular expression to determine mobile phone number or ID card method

1. What is a regular expression?

Regular expressions are text patterns that include normal characters (for example, letters between a to z) and special characters (called "metachars").

Regular expressions use a single string to describe and match a series of strings that match a syntactic rule.

2. Detailed code

1.Judge mobile phone number

Mobile phone number format:

The first digit must be 1 eleven numbers

The code is as follows (example):

// CheckMobile Check mobile phone numberfunc CheckMobile(phone string) bool {
	// Match rules	// ^1 The first position is one	// [345789]{1} followed by a number of 345789	// \\d \d Escape means the number {9} is connected to 9 bits	// $ ending character	regRuler := "^1[345789]{1}\\d{9}$"

	// Regular calling rules	reg := (regRuler)

	// Returns whether MatchString matches	return (phone)
}

2. Determine whether it is an ID card

The ID card format is:

15-digit or 18-digit number, when 18-digit number, the last digit may be X

The code is as follows (example):

// CheckIdCard check the ID cardfunc CheckIdCard(card string) bool {
	//18-bit ID card ^(\d{17})([0-9]|X)$	// Match rules	// (^\d{15}$) 15-digit ID card	// (^\d{18}$) 18-digit ID card	// (^\d{17}(\d|X|x)$) 18-bit ID card The last user with X	regRuler := "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)"

	// Regular calling rules	reg := (regRuler)

	// Returns whether MatchString matches	return (card)
}

Supplement: Golang mobile phone number and email address

//Mobile phone number verification rulesfunc PhoneCheckRule() string {
	return "^1[3|4|5|6|7|8|9][0-9]\\d{8}$"
}

//Email Verification Rulesfunc EmailCheckRule() string {
	return "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$"
}

Summarize

Through the above two examples, you can easily understand how to use regularity in Golang.

This is the article about Golang regular expression judging mobile phone number or ID card. For more information about Golang regular expression judging mobile phone number and ID card, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!