I need a regular expression which consist of: 1-3 digits and optional dot. It is something like IP pattern. I want my regex to allow the following:
192
192.
192.168
192.168.
and NOT the following:
192.1688
This is what I have so far:
preg_match('/^((\d{1,3})(\.?))+$/', $string);
But it still allows me to have more than 3 digits. Any suggestions how to fix the regex?
If you plan to match any number of 1-3 digit sequences separated with a dot (which is optional at the end), you can use
^\d{1,3}(?:\.\d{1,3})*\.?$
See demo
If you need the numbers to be in the range between 0
and 255
as in IP address, use
^(?:25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?))*\.?$
See another demo .
To limit to only 2 groups of numbers, use a ?
quantifier with the second non-capturing group:
^(?:25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[1-9][0-9]?))?\.?$
^
See the 3rd demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.