Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

regex - Validating IPv4 addresses with regexp

I've been trying to get an efficient regex for IPv4 validation, but without much luck. It seemed at one point I had had it with (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(.|$)){4}, but it produces some strange results:

$ grep --version
grep (GNU grep) 2.7
$ grep -E '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(.|$)){4}' <<< 192.168.1.1
192.168.1.1
$ grep -E '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(.|$)){4}' <<< 192.168.1.255
192.168.1.255
$ grep -E '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(.|$)){4}' <<< 192.168.255.255
$ grep -E '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(.|$)){4}' <<< 192.168.1.2555
192.168.1.2555

I did a search to see if this had already been asked and answered, but other answers appear to simply show how to determine 4 groups of 1-3 numbers, or do not work for me.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've already got a working answer but just in case you are curious what was wrong with your original approach, the answer is that you need parentheses around your alternation otherwise the (.|$) is only required if the number is less than 200.

'((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.|$)){4}'
    ^                                    ^

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...