Reputation: 82
I'm trying to make my own Regex to match IP along with * wildcard my own regex for now is :
^((((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\*){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){1,3}\*))$
but it's not working as I wish, I want to give regex given this conditions Ex.:
192.168.1.1 --> valid
192.168.1.* --> valid
192.168.*.* --> valid
192.*.*.* --> valid
192.168.*.1 --> invalid
192.*.1.1 --> invalid
192.*.*.1 --> invalid
*.168.1.1 --> invalid
Upvotes: 1
Views: 348
Reputation: 163207
One option is to use a positive lookahead to assert for 3 following dots with either 3 digits or a *
When matching you could make the *
the last part and optional.
^(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?=(?:\.(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|\*)){3}$)(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]))*(?:\.\*)*$
Another option is to spell out all the alternatives:
^(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.\*|(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.\*\.\*|\*\.\*\.\*)$
Upvotes: 4