We know that a complete domain name is composed of root domain, top-level domain, second-level, third-level... domain names, and each level of domain name is separated by dots, and each level of domain name is composed of letters, numbers and minus signs. (The first letter cannot be a minus sign), it is not case sensitive, and the length does not exceed 63.
A single name can be represented by a regularexpression[a-zA-Z0-9][-a-zA-Z0-9]{0,62} To match, the complete domain name includes at least two names (such as google.com, composed of google and com), and there can be a dot representing the root domain at the end (in the specification, the complete domain name is the one with a dot at the end, but It is generally considered that a domain name that includes more than two names is also a complete domain name, even if there is no dot after it).
Regular expression matching the complete domain name:
[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?
An IP string consists of four segments, each segment is a number from 0 to 255, segment Use decimal points to separate segments. For example, 61.139.2.69 is a legal IP string.
If the regular expression is written as \d{1,3}(\.\d{1,3}){3}, it is undoubtedly irresponsible, because it can match 300. Illegal IP strings such as 400.555.666.
To match a number between 0 and 255, there are several matching methods. The following is one of them:
Matching regular expression description
0 ~9 \d Single digit
10~99 [1-9]\d Two-digit number
100~199 1\d\d Three-digit number with hundreds as 1
200~249 2[0 -4]\d Three-digit number, the hundreds place is 2, the tens place is 0~9
250~255 25[0-5] Three-digit number, the hundreds place is 2, the tens place is 5, and the ones place is 0 ~5
Written as a regular expression, that is: (\d|([1-9]\d)|(1\d\d)|(2[0-4]\d)|(25 [0-5])), but when such a regular expression matches a string like 254, it will match 2, 5, and 4 respectively, resulting in 3 matches, which cannot achieve the expected effect. The correct way is to reverse the order as ((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d), because in (xxx|yyy) In this matching behavior, the search is done from left to right.
((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)(\.((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d)){3}
How to use regular expressions to highlight JavaScript code
Regular expression form verification Example introduction
#How to use regular expressions to match phone numbers, mobile phone numbers and email addresses
The above is the detailed content of How to use regular expressions to match IP addresses and domain names. For more information, please follow other related articles on the PHP Chinese website!