Taleb Ibrahim
Taleb Ibrahim

Reputation: 82

Java IP validation RegEx with wildcard *

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

Answers (1)

The fourth bird
The fourth bird

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]))*(?:\.\*)*$

Regex demo

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])\.\*\.\*|\*\.\*\.\*)$

Regex demo

Upvotes: 4

Related Questions