简体   繁体   中英

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM