Validating IPv4 addresses with regexp
Asked Answered
A

47

210

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 '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.1.1
192.168.1.1
$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.1.255
192.168.1.255
$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 192.168.255.255
$ grep -E '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?(\.|$)){4}\b' <<< 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.

Azerbaijan answered 12/3, 2011 at 17:27 Comment(2)
Don't forget that A, and A.B, and A.B.C are valid forms of IP address as well as A.B.C.D. Seriously. Try ping 2130706433 and ping 127.1 for a giggle.Wendalyn
My variant online regexr.com/39hqfHistorian
C
133

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.

'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
    ^                                    ^
Circumspect answered 12/3, 2011 at 18:8 Comment(10)
this appears to also validate things like 192.168.1.1.1Micrometeorite
Should it be: \b((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:(?<!\.)\b|\.)){4}; i.e. so it ends with a word boundary rather than with the end of line? Additionally here I've marked the non-capturing groups to avoid unwanted sub-matches. NB: This still doesn't take into account @dty's comment as I'm not familiar with that form of IP; though he's correct that it seems valid.Pomeroy
You might want to try this instead:((1?\d\d?|2[0-4]\d|25[0-5])\.){3}(1?\d\d?|2[0-4]\d|25[0-5])Autolysin
This works well for non capturing - \b(?:(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\bBrittni
If I want to add mask also the what will be the solution . Like I have IPv4 25[0-5]|2[0-4][0-9]|[01][0-9][0-9]/[0-9] I want to add / then Mask. So what will I add to have mask ? Ex: ..__.__ / __. Total of 15 character .Branen
Is 09.09.09.09 considered a valid IP? It also gets matched by this regex. But ping throws error message like ping: cannot resolve 09.09.09.09: Unknown host. I think it might be wise to reduce the matching to dot-decimal notation matching only. This entry discusses on leading errors in IP addresses.Nollie
This thing also validate cases like as 192.168.1.36.424.3232.1.0.3.0, 192.168.32.1.424, 9999.166.166.166.166, http://192.168.1.41, .....0.....1.2.3.0, weird:10.0.0.0.Cerebrum
Change pattern to ^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.|$)){4}\b to address the zero-padding issue on single digits.Ecto
Don't stop here, @danail-gabenski 's answer below offer another regex handling more edge cases.Sorkin
There is a small issue with it. I tried to fix it and here is the outcome: (25[0-5]|2[0-4]\d|1?\d{0,2})\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))Pelage
C
219

Best for Now (43 chars)

^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$

This version shortens things by another 6 characters while not making use of the negative lookahead, which is not supported in some regex flavors.

Newest, Shortest, Least Readable Version (49 chars)

^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$

The [0-9] blocks can be substituted by \d in 2 places - makes it a bit less readable, but definitely shorter.

Even Newer, even Shorter, Second least readable version (55 chars)

^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$

This version looks for the 250-5 case, after that it cleverly ORs all the possible cases for 200-249 100-199 10-99 cases. Notice that the |) part is not a mistake, but actually ORs the last case for the 0-9 range. I've also omitted the ?: non-capturing group part as we don't really care about the captured items, they would not be captured either way if we didn't have a full-match in the first place.

Old and shorter version (less readable) (63 chars)

^(?:(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(?!$)|$)){4}$

Older (readable) version (70 chars)

^(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(\.(?!$)|$)){4}$

It uses the negative lookahead (?!) to remove the case where the ip might end with a .

Alternative answer, using some of the newer techniques (71 chars)

^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]|)\d)$

Useful in regex implementations where lookaheads are not supported

Oldest answer (115 chars)

^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}
    (?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$

I think this is the most accurate and strict regex, it doesn't accept things like 000.021.01.0. it seems like most other answers here do and require additional regex to reject cases similar to that one - i.e. 0 starting numbers and an ip that ends with a .

Ceiba answered 21/4, 2016 at 5:1 Comment(43)
This is the only correct answer in this thread up to this date. The others miss such addresses as 0.0.0.0 or accept mixed octal/decimal notation like 033.033.33.033 or even allow 999.999.999.999. How about this regex which is 10 chars shorter than this answer: (([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])Governorship
Oops. Vicky also seems to have had supplied a correct one. His answer was downvoted, maybe because he did not explain why his was superior to the others. Upvoted his as well.Governorship
hey @Governorship yeah you could shorten it a bit with {2} otherwise you just reversed the order of matching which is fine as well. The othe problem would be that you need the ^ at the beginning and $ at the end of the regex in order to not match anything that deviates from the regex.Ceiba
As far as @vicky 's answer the problem is that it matches stuff like ..23.23 i.e. not sure why it's [0-9]? instead of just [0-9] for his last case. And again you do need the ^ and $ otherwise strings like 2555.100.232.10 are validated as correct, since it matches the last 55 from the 2555 number.Ceiba
Error on my end . It accepts 192.168, which it shouldn't.Kathleenkathlene
@JohndelfMiñao not sure how you got it to accept 192.168 because it's just 2 things where we require {4}. I assume you wanted to edit your comment and that you made an error ?Ceiba
Nope, I test it over and over again. It just accepts 192.168.Kathleenkathlene
@JohndelfMiñao hmm, I usually use regex101.com for checking my regular expressions. If you paste the regex in the top field and then in the test string field you type in "192.168." then select ECMAScript on the left it shouldn't highlight it for you. If you enter a valid ip v4 like 192.168.0.1 it should highlight it. Let me know.Ceiba
It worked on the test but did not worked in my validation. Currently use the regex for my angular validation.Kathleenkathlene
@JohndelfMiñao feel free to post a new question with your example and maybe me or someobdy else can help you figure it out - should be a pretty easy fix.Ceiba
@tinmarino I reverted your edit because it allowed things like 192.168.000.1 which is not a valid address. Anyone that wishes to edit this answer, please comment first here in order to avoid problems like these - I usually reply pretty fast. Always looking for a shorter/better solution of course.Ceiba
@DanailGabenski (and other) for memory, you solved it replacing last [01]?[0-9][0-9]? by 1[0-9]{2}|[1-9]?[0-9] because you don't like leading 0. Thank again ! I'll keep your solution in my regex master luggage.Charactery
@tinmarino yes, the dot-decimal format that has become standard for ipv4, although not officially accepted please look at the following. Specifically point 3, where a draft was suggested but expired. A secondary reason for being so strict with validation is that when presented in the UI, ip's with non-decimal numbers like 023 instead of 23 make users thing this is a mistake/bug. It also leads to difficulties with verification/security as 023 needs to be converted to 23 to avoid duplicates, etc. Thanks for trying to make things better !Ceiba
You can make it shorter by factoring out the [0-9] for the 2[0-4], 1, and shorter cases. ^(?:(25[0-5]|(?:2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$Hoagland
Thank you @ClaytonSingh ! I've gone ahead and made the change to the actual answer. I've also removed the non-capturing groups clause, which doesn't seem to affect the answer, but makes it a bit shorter, the answer is now aroud 48% of it's original length.Ceiba
$ echo "192.168.1.1" | grep -E '^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.(?!$)|$)){4}$' -- Did not work . Expected to matchPrepossessing
@Prepossessing try -P instead of -E, I was targeting the JavaScript syntax, but seems to be compatible with the PCRE one.Ceiba
In a case of hostname -I command this: hostname -I|perl -ne'print $& if $_=~/((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\.|(?=\s)|$)){4}/' appears to workTrice
@DanailGabenski beautiful Regex! But it still can be even shorter by using \d instead of [0-9]Doy
@DanailGabenski I am new to REGEX and I am studying your regex solution. I understand the first part of your answer, but am having a hard time decoding the second part of you answer. For me as a newbie, can you please explain the (\.(?!$)|$)){4}$ portion of your "Even Newer, even Shorter, Second least readable version" solution? I understand that \. is the escape sequence for the dot to follow after the expression specified in the first part of your solution. Thank youOnfre
@Onfre hey, I would recommend plugging the regex in a site like regex101.com and select the JavaScript syntax on the left, then enter a sample IP to match in the lower box. Now if you hover over any part of the regex you pasted in the top most box, it should show you what it's trying to match on the right of your screen - it's color coded and everything. The part you mentioned tries to match a DOT at the end if it's not the end of the line OR match the end of the line with no DOT beforehand. This works because we can have only 1 end of line and with {4} we require exactly 4 instances.Ceiba
Hi @DanailGabenski I made an edit to show a shortened version of the original using some of the newer patterns. I did this for regex implementations that don't support lookaheads, like the one used in Terraform. Hope it's not an issue!Czardom
An additional pattern I'd like to add (asking permission first this time!) is one that includes the CIDR notation. Something like this long form: ^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])[.]){3}(25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])[/](3[0-2]|[12][0-9]|[0-9])$ and this short form: ^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}[/](3[0-2]|[12][0-9]|[0-9])$. What do you think?Czardom
@Czardom I accepted the previous edit with some changes, see if those work for Terraform. I would say that the CIDR version is welcomed as well, just be sure to add one with the lookahead and one without it - also try to use the newest/shortest one for both of them. I'll do some testing on the one I accepted and the CIDR one to see if they are correct all the time. Thanks for contributing !Ceiba
Thanks! The \d syntax doesn't work in Terraform but seeing as this post is generally related to regex, and not specific to Terraform, I think it can stay with that syntax.Czardom
@Czardom looking at the Terraform documentation it does seem like \d and \D are supported so it should work. I'll take a look at the CIDR specs and try to add your contribution in a separate section below.Ceiba
Hmm, I tried but couldn't make it work.Czardom
Here's the regex I could come up with for the CIDR -> ^(((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.|)){4}((?<!\.)\/)(3[0-2]|[12]\d|\d))$ but I don't think it's entirely correct as depending on the CIDR value the allowed values for the IP change drastically. This would be a case for code doing the check if the IP is correct based on the CIDR - you would need like 32 different regexes at that point, so it might be optimal to just use the ipv4 regex and then check if the 4 resulting numbers are in the correct ranges. I was looking at terraform.io/language/functions/regex and \d is there.Ceiba
Any idea how I could modify the shortest regex to also include ports as in IP:PORT? I added :\d{1,4} or :([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]) at the end of ^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$ (before the $) but that didn't work.Shanonshanta
@Shanonshanta actually it's not that simple to deal with the port, but here is a sample regex similar to the one for the ip -> ^((6553[0-5])|(655[0-2][0-9])|(65[0-4][0-9]{2})|(6[0-4][0-9]{3})|([1-5][0-9]{4})|([0-5]{0,5})|([0-9]{1,4}))$ At this point it might be easier to split by : and then check if the resulting string is the same as a number - can't start with 0s and has to be between 0 and 65535 (including).Ceiba
@Shanonshanta Here is the shortest regex I could come up with that matches a ipv4 address and port (1-65535). ^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|:(([1-5]\d|[1-9])\d{0,3}|6(5(5(3[0-5]$|[0-2])|[0-4]\d)|[0-4]\d\d)\d?)$)){4}$ Match numbers 1-65535 ^(([1-5]\d|[1-9])\d{0,3}|6(5(5(3[0-5]$|[0-2])|[0-4]\d)|[0-4]\d\d)\d?)$ I am using a different approach since we have so many digits to match here by breaking into two primary cases. First numbers under 60000 using ([1-5]\d|[1-9])\d{0,3}. In the second case we deal with the numbers under 65535, by breaking off each digit at a time.Hoagland
You can replace "(\.(?!$)|$)" with "\.?\b" to make it shorter.Dhobi
Thanks @Dhobi I noticed your comment, but spent some time testing it and then forgot all about it - it's updated now !Ceiba
When I tested this one ^(?:(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(?!$)|$)){4}$ I found the $ at the end was redundant. I think this is because it is already accounted for in the preceding group.Sinistrality
@JamesFricker yeah I think that's correct, just use the latest and greatest though it's simpler and more efficient than this variant.Ceiba
Wow @DanailGabenski I just came back to this after over a year to find an even shorter one which doesn't use lookaheads! AWESOME! Impressive!Czardom
Here is the one that I do use: ^(?:(25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?1)$ . It has fewer steps to run, so should be faster.Blayze
@Blayze yeah this one seems to work for PCRE/2 but not any of the other flavors on regex101.com. It's also not shorter than the 43 character answer, as far as efficiency it matches group2 3 times, then matches group1 once which is pretty cool, but not sure if faster.Ceiba
You can change (?1) with \1 to make it work on more regexBlayze
@Blayze it doesn't match any IPs with the \1 change and is still not valid for other syntaxes as far as I can tell.Ceiba
regex101.com/r/Fl1BM9/1Blayze
Shortening [0-9] to \d is a bad idea because \d also covers non-Latin digits such as those represented in Arabic, Hebrew, Chinese, etc.Monomer
@Monomer this is an interesting point - do you have some examples of this that you can share, perhaps on regex101.com, please do select the ECMAScript Flavor on the left - but I guess if you find some flavors work while others don't let's just add them to the issue so people can keep them in mind. I tried personally with different language numbers to replicate \d matching them and it didn't work at all for some reason.Ceiba
C
133

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.

'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
    ^                                    ^
Circumspect answered 12/3, 2011 at 18:8 Comment(10)
this appears to also validate things like 192.168.1.1.1Micrometeorite
Should it be: \b((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:(?<!\.)\b|\.)){4}; i.e. so it ends with a word boundary rather than with the end of line? Additionally here I've marked the non-capturing groups to avoid unwanted sub-matches. NB: This still doesn't take into account @dty's comment as I'm not familiar with that form of IP; though he's correct that it seems valid.Pomeroy
You might want to try this instead:((1?\d\d?|2[0-4]\d|25[0-5])\.){3}(1?\d\d?|2[0-4]\d|25[0-5])Autolysin
This works well for non capturing - \b(?:(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\bBrittni
If I want to add mask also the what will be the solution . Like I have IPv4 25[0-5]|2[0-4][0-9]|[01][0-9][0-9]/[0-9] I want to add / then Mask. So what will I add to have mask ? Ex: ..__.__ / __. Total of 15 character .Branen
Is 09.09.09.09 considered a valid IP? It also gets matched by this regex. But ping throws error message like ping: cannot resolve 09.09.09.09: Unknown host. I think it might be wise to reduce the matching to dot-decimal notation matching only. This entry discusses on leading errors in IP addresses.Nollie
This thing also validate cases like as 192.168.1.36.424.3232.1.0.3.0, 192.168.32.1.424, 9999.166.166.166.166, http://192.168.1.41, .....0.....1.2.3.0, weird:10.0.0.0.Cerebrum
Change pattern to ^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(\.|$)){4}\b to address the zero-padding issue on single digits.Ecto
Don't stop here, @danail-gabenski 's answer below offer another regex handling more edge cases.Sorkin
There is a small issue with it. I tried to fix it and here is the outcome: (25[0-5]|2[0-4]\d|1?\d{0,2})\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))Pelage
H
118
^((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]?)$

Accept:

127.0.0.1
192.168.1.1
192.168.1.255
255.255.255.255
0.0.0.0
1.1.1.01        # This is an invalid IP address!

Reject:

30.168.1.255.1
127.1
192.168.1.256
-1.2.3.4
1.1.1.1.
3...3

Try online with unit tests: https://www.debuggex.com/r/-EDZOqxTxhiTncN6/1

Historian answered 22/9, 2014 at 7:46 Comment(9)
what about "3...3" ip address ? 3...3 is accepted using this regexDoig
What about 1.1.1.01? Is it considered a valid IPv4 address? Thanks.Recti
this regexp 1.1.1.01 consider as VALID IPv4 address. Online unit tests debuggex.com/r/-EDZOqxTxhiTncN6/1Historian
by the way ^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}$ get same result debuggex.com/r/mz_-0dEm3wseIKqK, pretty similar with @Mark Byers answerHistorian
@PriteshAcharya Works fine over here.Zacarias
@Sllouyssgort your shorter version does not work. It recognizes 1.1.1.1. (note the trailing dot) as a valid IP.Bullis
It is not very valid :) I edited your code in this way (25[0-5]|2[0-4]\d|1?\d{0,2})\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) and it works better and fasterPelage
false positive 1.1.1.00Granitite
most invalid IP address are matched. Check this regex demo.Tamtam
E
16

IPv4 address (accurate capture) Matches 0.0.0.0 through 255.255.255.255, but does capture invalid addresses such as 1.1.000.1 Use this regex to match IP numbers with accuracy. Each of the 4 numbers is stored into a capturing group, so you can access them for further processing.

\b
(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]?)\.
(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]?)
\b

taken from JGsoft RegexBuddy library

Edit: this (\.|$) part seems weird

Elapse answered 12/3, 2011 at 17:33 Comment(3)
Nice! I did a more efficient modification of that which seems to work: "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$){4}\b -- thanks!Azerbaijan
@MatthieuCartier Your efficient regex pattern didn't work for me,Mellar
255.255.255.000 is not a valid IPBackset
W
12

I think many people reading this post will be looking for simpler regular expressions, even if they match some technically invalid IP addresses. (And, as noted elsewhere, regex probably isn't the right tool for properly validating an IP address anyway.)

Remove ^ and, where applicable, replace $ with \b, if you don't want to match the beginning/end of the line.

Basic Regular Expression (BRE) (tested on GNU grep, GNU sed, and vim):

/^[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+$/

Extended Regular Expression (ERE):

/^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/

or:

/^([0-9]+(\.|$)){4}/

Perl-compatible Regular Expression (PCRE) (tested on Perl 5.18):

/^\d+\.\d+\.\d+\.\d+$/

or:

/^(\d+(\.|$)){4}/

Ruby (tested on Ruby 2.1):

Although supposed to be PCRE, Ruby for whatever reason allowed this regex not allowed by Perl 5.18:

/^(\d+[\.$]){4}/

My tests for all these are online here.

Weinman answered 2/7, 2018 at 9:0 Comment(1)
Your: /^(\d+[\.$]){4}/ is for 5.5.5.5. not 5.5.5.5Soracco
W
9

I was in search of something similar for IPv4 addresses - a regex that also stopped commonly used private ip addresses from being validated (192.168.x.y, 10.x.y.z, 172.16.x.y) so used negative look aheads to accomplish this:

(?!(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.).*)
(?!255\.255\.255\.255)(25[0-5]|2[0-4]\d|[1]\d\d|[1-9]\d|[1-9])
(\.(25[0-5]|2[0-4]\d|[1]\d\d|[1-9]\d|\d)){3}

(These should be on one line of course, formatted for readability purposes on 3 separate lines) Regular expression visualization

Debuggex Demo

It may not be optimised for speed, but works well when only looking for 'real' internet addresses.

Things that will (and should) fail:

0.1.2.3         (0.0.0.0/8 is reserved for some broadcasts)
10.1.2.3        (10.0.0.0/8 is considered private)
172.16.1.2      (172.16.0.0/12 is considered private)
172.31.1.2      (same as previous, but near the end of that range)
192.168.1.2     (192.168.0.0/16 is considered private)
255.255.255.255 (reserved broadcast is not an IP)
.2.3.4
1.2.3.
1.2.3.256
1.2.256.4
1.256.3.4
256.2.3.4
1.2.3.4.5
1..3.4

IPs that will (and should) work:

1.0.1.0         (China)
8.8.8.8         (Google DNS in USA)
100.1.2.3       (USA)
172.15.1.2      (USA)
172.32.1.2      (USA)
192.167.1.2     (Italy)

Provided in case anybody else is looking for validating 'Internet IP addresses not including the common private addresses'

Wedge answered 9/11, 2015 at 21:28 Comment(0)
R
6

''' This code works for me, and is as simple as that.

Here I have taken the value of ip and I am trying to match it with regex.

ip="25.255.45.67"    

op=re.match('(\d+).(\d+).(\d+).(\d+)',ip)

if ((int(op.group(1))<=255) and (int(op.group(2))<=255) and int(op.group(3))<=255) and (int(op.group(4))<=255)):

print("valid ip")

else:

print("Not valid")

Above condition checks if the value exceeds 255 for all the 4 octets then it is not a valid. But before applying the condition we have to convert them into integer since the value is in a string.

group(0) prints the matched output, Whereas group(1) prints the first matched value and here it is "25" and so on. '''

Recluse answered 17/3, 2019 at 8:58 Comment(2)
Welcome to StackOverflow. If you could spend some words on why your answer should solve the OP issue, would be great. Only-code answers are generally bad answers as they don't help fellow coders understand what they had done wrong.Berezniki
Use proper indenting in your code to make it readable for the usersClip
D
6

Here is a better one with passing/failing IPs attached

/^((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$/

Accepts

127.0.0.1
192.168.1.1
192.168.1.255
255.255.255.255
10.1.1.1
0.0.0.0

Rejects

1.1.1.01
30.168.1.255.1
127.1
192.168.1.256
-1.2.3.4
1.1.1.1.
3...3
192.168.1.099
Deirdredeism answered 23/6, 2021 at 16:58 Comment(0)
S
5

Above answers are valid but what if the ip address is not at the end of line and is in between text.. This regex will even work on that.

code: '\b((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.)){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\b'

input text file:

ip address 0.0.0.0 asfasf
 sad sa 255.255.255.255 cvjnzx
zxckjzbxk  999.999.999.999 jshbczxcbx
sjaasbfj 192.168.0.1 asdkjaksb
oyo 123241.24121.1234.3423 yo
yo 0000.0000.0000.0000 y
aw1a.21asd2.21ad.21d2
yo 254.254.254.254 y0
172.24.1.210 asfjas
200.200.200.200
000.000.000.000
007.08.09.210
010.10.30.110

output text:

0.0.0.0
255.255.255.255
192.168.0.1
254.254.254.254
172.24.1.210
200.200.200.200
Sludgy answered 23/11, 2018 at 7:32 Comment(0)
G
5
/^(?:(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(?1)$/m

Demo

Gaucho answered 10/6, 2019 at 11:58 Comment(1)
note: this works in Perl, but no Java :-(Neglect
T
4

I managed to construct a regex from all other answers.

(25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]|[0-9]?)(\.(25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]|[0-9]?)){3}
Toul answered 12/10, 2015 at 11:52 Comment(1)
As per the IEEE 802.x ethernet standard the IP validation is IP range 0.x.x.x >>> should not be allowed - invalid IP. #1.The IP range starts from 1.x.x.x to 126.x.x.x >>>> can be allowed to configure. #2.IP range 127.x.x.x >>>> should not be allowed - invalid IP. #3.IP range 128.x.x.x to 223.x.x.x >> can be allowed to configure. the better way to handle is suggested as below: ^(22[0-3]|2[0-1][0-9]|[1][0-9][0-9]?|[1-9][0-9]|[1-9])\.(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]?)\.(25[0-4]|2[0-4][0-9]|[01]?[0-9][0-9]?)$Gershom
P
4

This is a little longer than some but this is what I use to match IPv4 addresses. Simple with no compromises.

^((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])$
Perverse answered 24/12, 2017 at 9:13 Comment(0)
U
4

For number from 0 to 255 I use this regex:

(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))

Above regex will match integer number from 0 to 255, but not match 256.

So for IPv4 I use this regex:

^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})$

It is in this structure: ^(N)((\.(N)){3})$ where N is the regex used to match number from 0 to 255.
This regex will match IP like below:

0.0.0.0
192.168.1.2

but not those below:

10.1.0.256
1.2.3.
127.0.1-2.3

For IPv4 CIDR (Classless Inter-Domain Routing) I use this regex:

^(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))$

It is in this structure: ^(N)((\.(N)){3})\/M$ where N is the regex used to match number from 0 to 255, and M is the regex used to match number from 0 to 32.
This regex will match CIDR like below:

0.0.0.0/0
192.168.1.2/32

but not those below:

10.1.0.256/16
1.2.3./24
127.0.0.1/33

And for list of IPv4 CIDR like "10.0.0.0/16", "192.168.1.1/32" I use this regex:

^("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))")((,([ ]*)("(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))((\.(([0-9])|([1-9][0-9])|(1([0-9]{2}))|(2[0-4][0-9])|(25[0-5]))){3})\/(([0-9])|([12][0-9])|(3[0-2]))"))*)$

It is in this structure: ^(“C”)((,([ ]*)(“C”))*)$ where C is the regex used to match CIDR (like 0.0.0.0/0).
This regex will match list of CIDR like below:

“10.0.0.0/16”,”192.168.1.2/32”, “1.2.3.4/32”

but not those below:

“10.0.0.0/16” 192.168.1.2/32 “1.2.3.4/32”

Maybe it might get shorter but for me it is easy to understand so fine by me.

Hope it helps!

Undoubted answered 16/8, 2019 at 8:26 Comment(1)
Welcome to SO, we appreciate your input! Could you please elaborate a bit on what the different regex' are doing (in particular the last one)?Oswell
M
3
(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2}))\.){3}(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2})))

Test to find matches in text, https://regex101.com/r/9CcMEN/2

Following are the rules defining the valid combinations in each number of an IP address:

  • Any one- or two-digit number.
  • Any three-digit number beginning with 1.

  • Any three-digit number beginning with 2 if the second digit is 0 through 4.

  • Any three-digit number beginning with 25 if the third digit is 0 through 5.

Let'start with (((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2}))\.), a set of four nested subexpressions, and we’ll look at them in reverse order. (\d{1,2}) matches any one- or two-digit number or numbers 0 through 99. (1\d{2}) matches any three-digit number starting with 1 (1 followed by any two digits), or numbers 100 through 199. (2[0-4]\d) matches numbers 200 through 249. (25[0-5]) matches numbers 250 through 255. Each of these subexpressions is enclosed within another subexpression with an | between each (so that one of the four subexpressions has to match, not all). After the range of numbers comes \. to match ., and then the entire series (all the number options plus \.) is enclosed into yet another subexpression and repeated three times using {3}. Finally, the range of numbers is repeated (this time without the trailing \.) to match the final IP address number. By restricting each of the four numbers to values between 0 and 255, this pattern can indeed match valid IP addresses and reject invalid addresses.

Excerpt From: Ben Forta. “Learning Regular Expressions.”


If neither a character is wanted at the beginning of IP address nor at the end, ^ and $ metacharacters ought to be used, respectively.

^(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2}))\.){3}(((25[0-5])|(2[0-4]\d)|(1\d{2})|(\d{1,2})))$

Test to find matches in text, https://regex101.com/r/uAP31A/1

Marentic answered 1/6, 2018 at 20:19 Comment(0)
A
3

Find a valid ip address in the text is a very difficult problem


I have a regexp, that match (extract) valid ip addresses from strings in text files.

my regexp

\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){2}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\b
  • \b word boundary
  • (?: - means start non capturing group
  • ^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.) - string must start with first right octet with dot char
    • (?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9]) - find first right octet - (firt octet can not start with - 0)
  • (?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){2} - find next right two octets with dot string
  • (?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\b - string must end with right fourth octet (now zero char is allowed)

But this ip regexp has a minority false positive matches:

https://regexr.com/69dk7

regexp for mostly right match for ip addresses

Find or extract valid ip address from text file with only regexp is impossible. Without checking another conditions you always get false positive matches.

Solution


I write one liner perl for extract ip addresses from text files. It has this conditions:

  • when the ip address is at the beginning of the line, the next char is one or multiple whitespace char (space, tab, new line...)
  • when ip address is at end of line, the new line is next char and before ip address is one or multiple whitespace chars
  • in middle of text - before and after ip address is one or multiple whitespace chars

The consequence is that perl not match strings like https://84.25.74.125 and another URI strings. Or ip addres at the end of line with dot char at the end. But it find any valid ip address in the text.

perl one liner solution:

$ cat ip.txt | perl -lane 'use warnings; use strict; for my $i (@F){if ($i =~/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[1-9])\.)(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){2}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/) { print $i; } }'
36.42.84.233
158.22.45.0
36.84.84.233
12.0.5.4
1.25.45.36
255.3.6.5
4.255.2.1
127.0.0.1
127.0.0.5
126.0.0.1

testing text file:

$ cat ip.txt
36.42.84.233 stop 158.22.45.0 and 56.32.58.2.
25.36.84.84abc and abc2.4.8.2 is error.
1.2.3.4_
But false positive is 2.2.2.2.2.2.2.2 or 1.1.1.1.1
http://23.54.212.1:80
https://89.35.248.1/abc
36.84.84.233 was 25.36.58.4/abc/xyz&158.133.26.4&another_var
and 42.27.0.1:8333 in http://212.158.45.2:26
0.25.14.15 ip can not start with zero
2.3.0
abc 12.0.5.4
1.25.45.36
12.05.2.5
256.1.2.5
255.3.6.5
4.255.2.1
4.256.5.6
127.0.0.1 is localhost.
this ip 127.0.0.5 is not localhost
126.0.0.1

Appendix


For people from another planets for whom the strings 2130706433, 127.1, 24.005.04.52 is a valid ip address I have a message: Try to find a solution yourself!!!

Assent answered 12/11, 2021 at 12:23 Comment(0)
D
2

IPv4 address is a very complicated thing.

Note: Indentation and lining are only for illustration purposes and do not exist in the real RegEx.

\b(
  ((
    (2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
  |
    0[Xx]0*[0-9A-Fa-f]{1,2}
  |
    0+[1-3]?[0-9]{1,2}
  )\.){1,3}
  (
    (2(5[0-5]|[0-4][0-9])|1[0-9]{2}|[1-9]?[0-9])
  |
    0[Xx]0*[0-9A-Fa-f]{1,2}
  |
    0+[1-3]?[0-9]{1,2}
  )
|
  (
    [1-3][0-9]{1,9}
  |
    [1-9][0-9]{,8}
  |
    (4([0-1][0-9]{8}
      |2([0-8][0-9]{7}
        |9([0-3][0-9]{6}
          |4([0-8][0-9]{5}
            |9([0-5][0-9]{4}
              |6([0-6][0-9]{3}
                |7([0-1][0-9]{2}
                  |2([0-8][0-9]{1}
                    |9([0-5]
    ))))))))))
  )
|
  0[Xx]0*[0-9A-Fa-f]{1,8}
|
  0+[1-3]?[0-7]{,10}
)\b

These IPv4 addresses are validated by the above RegEx.

127.0.0.1
2130706433
0x7F000001
017700000001
0x7F.0.0.01 # Mixed hex/dec/oct
000000000017700000001 # Have as many leading zeros as you want
0x0000000000007F000001 # Same as above
127.1
127.0.1

These are rejected.

256.0.0.1
192.168.1.099 # 099 is not a valid number
4294967296 # UINT32_MAX + 1
0x100000000
020000000000
Demi answered 24/12, 2017 at 9:34 Comment(0)
C
2

Valid regex for IPV4 address for Java

^((\\d|[1-9]\\d|[0-1]\\d{2}|2[0-4]\\d|25[0-5])[\\.]){3}(\\d|[1-9]\\d|[0-1]\\d{2}|2[0-4]\\d|25[0-5])$
Chuckle answered 25/1, 2020 at 13:27 Comment(1)
I've tried some from this post but none of those did pass code signal test but this one passed. Thanks!Radix
H
2

Considering some variants suggested, \d and \b may not be supported. Hence, just in case:

IPv4 address

^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)$

Test: https://debuggex.com/r/izHiog3KkYztRMSJ

graph

Holmic answered 23/9, 2022 at 14:46 Comment(0)
S
2

The shortest pattern is not necessarily the most efficient. I prefer

^(?:\b\.?(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){4}$

which is a good tradeoff between pattern-length and efficiency.

Here is a demo at regex101

This pattern works by use of a \b word boundary and making the dot optional. The word boundary will still require a dot between each 0-255. Placement of \b disallows a dot at the ^ start.

Certainly by use of ( capturing ) instead of (?: non-capturing ) groups four characters can be spared but why capture anything without reason? No part gets reused or would be extracted.

The only reason that makes sense would be, if non-capturing groups are not supported.


Without validating 0-255 and allowing any one to three digits: ^(?:\b\.?\d{1,3}){4}$

Seals answered 25/9, 2023 at 11:37 Comment(0)
D
1

With subnet mask :

^$|([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\
.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\
.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\
.([01]?\\d\\d?|2[0-4]\\d|25[0-5])
((/([01]?\\d\\d?|2[0-4]\\d|25[0-5]))?)$
Dillard answered 5/4, 2018 at 15:33 Comment(0)
Q
1

I tried to make it a bit simpler and shorter.

^(([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])$

If you are looking for java/kotlin:

^(([01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d{1,2}|2[0-4]\\d|25[0-5])$

If someone wants to know how it works here is the explanation. It's really so simple. Just give it a try :p :

 1. ^.....$: '^' is the starting and '$' is the ending.

 2. (): These are called a group. You can think of like "if" condition groups.

 3. |: 'Or' condition - as same as most of the programming languages.

 4. [01]?\d{1,2}: '[01]' indicates one of the number between 0 and 1. '?' means '[01]' is optional. '\d' is for any digit between 0-9 and '{1,2}' indicates the length can be between 1 and 2. So here the number can be 0-199.

 5. 2[0-4]\d: '2' is just plain 2. '[0-4]' means a number between 0 to 4. '\d' is for any digit between 0-9. So here the number can be 200-249.

 6. 25[0-5]: '25' is just plain 25. '[0-5]' means a number between 0 to 5. So here the number can be 250-255.

 7. \.: It's just plan '.'(dot) for separating the numbers.

 8. {3}: It means the exact 3 repetition of the previous group inside '()'.

 9. ([01]?\d{1,2}|2[0-4]\d|25[0-5]): Totally same as point 2-6

Mathematically it is like:

(0-199 OR 200-249 OR 250-255).{Repeat exactly 3 times}(0-199 OR 200-249 OR 250-255)

So, as you can see normally this is the pattern for the IP addresses. I hope it helps to understand Regular Expression a bit. :p

Quiddity answered 26/12, 2019 at 4:45 Comment(0)
Q
1

I tried to make it a bit simpler and shorter.

^(([01]?\d{1,2}|2[0-4]\d|25[0-5]).){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])$

If you are looking for java/kotlin:

^(([01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}([01]?\d{1,2}|2[0-4]\d|25[0-5])$

If someone wants to know how it works here is the explanation. It's really so simple. Just give it a try :p :

 1. ^.....$: '^' is the starting and '$' is the ending.

 2. (): These are called a group. You can think of like "if" condition groups.

 3. |: 'Or' condition - as same as most of the programming languages.

 4. [01]?\d{1,2}: '[01]' indicates one of the number between 0 and 1. '?' means '[01]' is optional. '\d' is for any digit between 0-9 and '{1,2}' indicates the length can be between 1 and 2. So here the number can be 0-199.

 5. 2[0-4]\d: '2' is just plain 2. '[0-4]' means a number between 0 to 4. '\d' is for any digit between 0-9. So here the number can be 200-249.

 6. 25[0-5]: '25' is just plain 25. '[0-5]' means a number between 0 to 5. So here the number can be 250-255.

 7. \.: It's just plan '.'(dot) for separating the numbers.

 8. {3}: It means the exact 3 repetition of the previous group inside '()'.

 9. ([01]?\d{1,2}|2[0-4]\d|25[0-5]): Totally same as point 2-6

Mathematically it is like:

(0-199 OR 200-249 OR 250-255).{Repeat exactly 3 times}(0-199 OR 200-249 OR 250-255)

So, as you can see normally this is the pattern for the IP addresses. I hope it helps to understand Regular Expression a bit. :p

Quiddity answered 26/12, 2019 at 4:49 Comment(0)
H
1

To validate any IP address in the valid range 0.0.0.0 to 255.255.255.255 can be written in very simple form as below.

((1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])
Horowitz answered 9/10, 2021 at 1:44 Comment(0)
W
1

don't reinvent the wheel ;)

the best way is to use well written and tested library

npm @sideway/address has 6M weekly downloads

import { ipRegex } from "@sideway/address";

const { regex } = ipRegex({ version: ['ipv4'], cidr: 'forbidden' });

the regex for ipv4 without cidr is:

/^(?:(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))$/

unit tested on:

const validIPv4sWithoutCidr = [
  '0.0.0.0',
  '255.255.255.255',
  '127.0.0.1',
  '192.168.2.1',
  '0.0.0.3',
  '0.0.0.7',
  '0.0.0.15',
  '0.0.0.31',
  '0.0.0.63',
  '0.0.0.127',
  '01.020.030.100',
  '0.0.0.0',
  '00.00.00.00',
  '000.000.000.000'
];

but you can easily with (without) options match other versions and be sure it covers all possibilities

import { ipRegex } from "@sideway/address";

const { regex } = ipRegex();

/^(?:(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?:\/(?:\d|[1-2]\d|3[0-2]))?|(?:(?:[\dA-Fa-f]{1,4}:){6}(?:[\dA-Fa-f]{1,4}:[\dA-Fa-f]{1,4}|(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|::(?:[\dA-Fa-f]{1,4}:){5}(?:[\dA-Fa-f]{1,4}:[\dA-Fa-f]{1,4}|(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(?:[\dA-Fa-f]{1,4})?::(?:[\dA-Fa-f]{1,4}:){4}(?:[\dA-Fa-f]{1,4}:[\dA-Fa-f]{1,4}|(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(?:(?:[\dA-Fa-f]{1,4}:){0,1}[\dA-Fa-f]{1,4})?::(?:[\dA-Fa-f]{1,4}:){3}(?:[\dA-Fa-f]{1,4}:[\dA-Fa-f]{1,4}|(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(?:(?:[\dA-Fa-f]{1,4}:){0,2}[\dA-Fa-f]{1,4})?::(?:[\dA-Fa-f]{1,4}:){2}(?:[\dA-Fa-f]{1,4}:[\dA-Fa-f]{1,4}|(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(?:(?:[\dA-Fa-f]{1,4}:){0,3}[\dA-Fa-f]{1,4})?::[\dA-Fa-f]{1,4}:(?:[\dA-Fa-f]{1,4}:[\dA-Fa-f]{1,4}|(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(?:(?:[\dA-Fa-f]{1,4}:){0,4}[\dA-Fa-f]{1,4})?::(?:[\dA-Fa-f]{1,4}:[\dA-Fa-f]{1,4}|(?:(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:0{0,2}\d|0?[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(?:(?:[\dA-Fa-f]{1,4}:){0,5}[\dA-Fa-f]{1,4})?::[\dA-Fa-f]{1,4}|(?:(?:[\dA-Fa-f]{1,4}:){0,6}[\dA-Fa-f]{1,4})?::)(?:\/(?:0{0,2}\d|0?[1-9]\d|1[01]\d|12[0-8]))?|v[\dA-Fa-f]+\.[\w-\.~!\$&'\(\)\*\+,;=:]+(?:\/(?:0{0,2}\d|0?[1-9]\d|1[01]\d|12[0-8]))?)$/

Wert answered 22/3, 2023 at 9:29 Comment(0)
J
0
    const char*ipv4_regexp = "\\b(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]?)\\."
    "(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]?)\\b";

I adapted the regular expression taken from JGsoft RegexBuddy library to C language (regcomp/regexec) and I found out it works but there's a little problem in some OS like Linux. That regular expression accepts ipv4 address like 192.168.100.009 where 009 in Linux is considered an octal value so the address is not the one you thought. I changed that regular expression as follow:

    const char* ipv4_regex = "\\b(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
           "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
           "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
           "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\b";

using that regular expressione now 192.168.100.009 is not a valid ipv4 address while 192.168.100.9 is ok.

I modified a regular expression for multicast address too and it is the following:

    const char* mcast_ipv4_regex = "\\b(22[4-9]|23[0-9])\\."
                        "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\."
                        "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9]?)\\."
                        "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\b";

I think you have to adapt the regular expression to the language you're using to develop your application

I put an example in java:

    package utility;

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;

    public class NetworkUtility {

        private static String ipv4RegExp = "\\b(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d?)\\b";

        private static String ipv4MulticastRegExp = "2(?:2[4-9]|3\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d?|0)){3}";

        public NetworkUtility() {

        }

        public static boolean isIpv4Address(String address) {
            Pattern pattern = Pattern.compile(ipv4RegExp);
            Matcher matcher = pattern.matcher(address);

            return matcher.matches();
        }

        public static boolean isIpv4MulticastAddress(String address) {
             Pattern pattern = Pattern.compile(ipv4MulticastRegExp);
             Matcher matcher = pattern.matcher(address);

             return matcher.matches();
        }
    }
Justitia answered 10/8, 2014 at 8:27 Comment(0)
S
0
-bash-3.2$ echo "191.191.191.39" | egrep 
  '(^|[^0-9])((2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)\.{3}
     (2([6-9]|5[0-5]?|[0-4][0-9]?)?|1([0-9][0-9]?)?|[3-9][0-9]?|0)($|[^0-9])'

>> 191.191.191.39

(This is a DFA that matches the entire addr space (including broadcasts, etc.) and nothing else.

Sauterne answered 21/2, 2016 at 11:14 Comment(0)
T
0

I think this one is the shortest.

^(([01]?\d\d?|2[0-4]\d|25[0-5]).){3}([01]?\d\d?|2[0-4]\d|25[0-5])$
Taft answered 9/9, 2016 at 8:38 Comment(0)
A
0

I found this sample very useful, furthermore it allows different ipv4 notations.

sample code using python:

    def is_valid_ipv4(ip4):
    """Validates IPv4 addresses.
    """
    import re
    pattern = re.compile(r"""
        ^
        (?:
          # Dotted variants:
          (?:
            # Decimal 1-255 (no leading 0's)
            [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
          |
            0x0*[0-9a-f]{1,2}  # Hexadecimal 0x0 - 0xFF (possible leading 0's)
          |
            0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's)
          )
          (?:                  # Repeat 0-3 times, separated by a dot
            \.
            (?:
              [3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
            |
              0x0*[0-9a-f]{1,2}
            |
              0+[1-3]?[0-7]{0,2}
            )
          ){0,3}
        |
          0x0*[0-9a-f]{1,8}    # Hexadecimal notation, 0x0 - 0xffffffff
        |
          0+[0-3]?[0-7]{0,10}  # Octal notation, 0 - 037777777777
        |
          # Decimal notation, 1-4294967295:
          429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}|
          42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}|
          4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8}
        )
        $
    """, re.VERBOSE | re.IGNORECASE)
    return pattern.match(ip4) <> None
Ageold answered 9/3, 2017 at 10:58 Comment(0)
H
0
((\.|^)(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0$)){4}

This regex will not accept 08.8.8.8 or 8.08.8.8 or 8.8.08.8 or 8.8.8.08

Hispania answered 20/7, 2017 at 13:40 Comment(3)
this one misses for example 127.0.0.1 and 0.0.0.0Governorship
^((\.|^)(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|[0-9]?|0))((\.|^)(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)){2}.((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)$)Hispania
It is correct to reject leading zeros, according to the spec.Memphian
T
0

Finds a valid IP addresses as long as the IP is wrapped around any character other than digits (behind or ahead the IP). 4 Backreferences created: $+{first}.$+{second}.$+{third}.$+{forth}

Find String:
#any valid IP address
(?<IP>(?<![\d])(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))
#only valid private IP address RFC1918
(?<IP>(?<![\d])(:?(:?(?<first>10)[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5])))|(:?(?<first>172)[\.](?<second>(:?1[6-9])|(:?2[0-9])|(:?3[0-1])))|(:?(?<first>192)[\.](?<second>168)))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))

Notepad++ Replace String Option 1: Replaces the whole IP (NO Change):
$+{IP}

Notepad++ Replace String Option 2: Replaces the whole IP octect by octect (NO Change)
$+{first}.$+{second}.$+{third}.$+{forth}

Notepad++ Replace String Option 3: Replaces the whole IP octect by octect (replace 3rd octect value with 0)
$+{first}.$+{second}.0.$+{forth}
NOTE: The above will match any valid IP including 255.255.255.255 for example and change it to 255.255.0.255 which is wrong and not very useful of course.

Replacing portion of each octect with an actual value however you can build your own find and replace which is actual useful to ammend IPs in text files:

for example replace the first octect group of the original Find regex above:
(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))
with
(?<first>10)

and
(?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))
with
(?<second>216)
and you are now matching addresses starting with first octect 192 only

Find on notepad++:
(?<IP>(?<![\d])(?<first>10)[\.](?<second>216)[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))

You could still perform Replace using back-referece groups in the exact same fashion as before.

You can get an idea of how the above matched below:

cat ipv4_validation_test.txt
Full Match:
0.0.0.1
12.108.1.34
192.168.1.1
10.249.24.212
10.216.1.212
192.168.1.255
255.255.255.255
0.0.0.0


Partial Match (IP Extraction from line)
30.168.1.0.1
-1.2.3.4
sfds10.216.24.23kgfd
da11.15.112.255adfdsfds
sfds10.216.24.23kgfd


NO Match
1.1.1.01
3...3
127.1.
192.168.1..
192.168.1.256
da11.15.112.2554adfdsfds
da311.15.112.255adfdsfds

Using grep you can see the results below:

From grep:
grep -oP '(?<IP>(?<![\d])(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))' ipv4_validation_test.txt
0.0.0.1
12.108.1.34
192.168.1.1
10.249.24.212
10.216.1.212
192.168.1.255
255.255.255.255
0.0.0.0
30.168.1.0
1.2.3.4
10.216.24.23
11.15.112.255
10.216.24.23


grep -P '(?<IP>(?<![\d])(?<first>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<second>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))' ipv4_validation_test.txt
0.0.0.1
12.108.1.34
192.168.1.1
10.249.24.212
10.216.1.212
192.168.1.255
255.255.255.255
0.0.0.0
30.168.1.0.1
-1.2.3.4
sfds10.216.24.23kgfd
da11.15.112.255adfdsfds
sfds10.216.24.23kgfd


#matching ip addresses starting with 10.216
grep -oP '(?<IP>(?<![\d])(?<first>10)[\.](?<second>216)[\.](?<third>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))[\.](?<forth>(:?\d)|(:?[1-9]\d)|(:?1\d{2})|(:?2[0-4]\d)|(:?25[0-5]))(?![\d]))' ipv4_validation_test.txt
10.216.1.212
10.216.24.23
10.216.24.23
Tertian answered 13/9, 2017 at 22:19 Comment(0)
A
0

^((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]?))$


Above will be regex for the ip address like: 221.234.000.112 also for 221.234.0.112, 221.24.03.112, 221.234.0.1


You can imagine all kind of address as above

Antic answered 12/4, 2018 at 15:20 Comment(0)
A
0

I would use PCRE and the define keyword:

/^
 ((?&byte))\.((?&byte))\.((?&byte))\.((?&byte))$
 (?(DEFINE)
     (?<byte>25[0-5]|2[0-4]\d|[01]?\d\d?))
/gmx

Demo: https://regex101.com/r/IB7j48/2

The reason of this is to avoid repeating the (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) pattern four times. Other solutions such as the one below work well, but it does not capture each group as it would be requested by many.

/^((\d+?)(\.|$)){4}/ 

The only other way to have 4 capture groups is to repeat the pattern four times:

/^(?<one>\d+)\.(?<two>\d+)\.(?<three>\d+)\.(?<four>\d+)$/

Capturing a ipv4 in perl is therefore very easy

$ echo "Hey this is my IP address 138.131.254.8, bye!" | \
  perl -ne 'print "[$1, $2, $3, $4]" if \
    /\b((?&byte))\.((?&byte))\.((?&byte))\.((?&byte))
     (?(DEFINE)
        \b(?<byte>25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))
    /x'

[138, 131, 254, 8]
Accrual answered 9/6, 2018 at 11:48 Comment(0)
C
0

The most precise, straightforward and compact IPv4 regexp I can imagine is

^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$

But what about the performance/efficiency of ... Sorry I don't know, who cares?

Chalcedony answered 9/6, 2018 at 14:48 Comment(0)
G
0

Try this:

\b(([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\.(2[0-5][0-5]|1[0-9][0-9]|[1-9][0-9]|[1-9]))\b
Gerbold answered 18/7, 2018 at 8:56 Comment(0)
P
0
ip address can be from 0.0.0.0 to 255.255.255.255

(((0|1)?[0-9][0-9]?|2[0-4][0-9]|25[0-5])[.]){3}((0|1)?[0-9][0-9]?|2[0-4][0-9]|25[0-5])$

(0|1)?[0-9][0-9]? - checking value from 0 to 199
2[0-4][0-9]- checking value from 200 to 249
25[0-5]- checking value from 250 to 255
[.] --> represent verify . character 
{3} --> will match exactly 3
$ --> end of string
Placket answered 3/9, 2018 at 16:15 Comment(0)
A
0

Following is the regex expression to validate the IP-Address.

^((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]?)$
Aliciaalick answered 12/12, 2018 at 21:20 Comment(0)
P
0

Easy way

((25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]{0,1})\.){3}(25[0-5]|2[0-4][0-9]|[1][0-9][0-9]|[1-9][0-9]{0,1})

Demo

Pusey answered 18/12, 2018 at 14:15 Comment(0)
B
0

This one matches only valid IPs (no prepended 0's, but it will match octets from 0-255 regardless of their 'function' [ie reserved, private, etc]) and allows for inline matching, where there may be spaces before and/or after the IP, or when using CIDR notation.

grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)'

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '10.0.1.2'
10.0.1.2

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2'
ip address 10.0.1.2

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2 255.255.255.255'
ip address 10.0.1.2 255.255.255.255

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2/32'
ip address 10.0.1.2/32

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address 10.0.1.2.32'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< 'ip address10.0.1.2'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '10.0.1.256'
$

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '0.0.0.0'
0.0.0.0

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '255.255.255.255'
255.255.255.255

$ grep -E '(^| )((([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\.){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])($| |/)' <<< '255.255.255.256'
$

Of course, in cases where the IP is inline, you can use grep option "-o" and your preference of whitespace trimmer if you just want the whole IP and nothing but the IP.

For those of us using python, the equivalent is roughly:

>>> ipv4_regex = re.compile(r'(^| )((?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])($| |/)')
>>> ipv4_regex.search('ip address 10.1.2.3/32')
<re.Match object; span=(10, 20), match=' 10.1.2.3/'>

If you're picky (lazy) like me, you probably would prefer to use grouping to get the whole IP and nothing but the IP, or the CIDR and nothing but the CIDR or some combination thereof. We can use (?P) syntax to name our groups for easier reference.

>>> ipv4_regex = re.compile(r'(?:^| )(?P<address>((?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(?:[1-9]?\d|1\d{2}|2[0-4]\d|25[0-5]))(?P<slash>/)?(?(slash)(?P<cidr>[0-9]|[12][0-9]|3[0-2]))(?:$| )')
>>> match = ipv4_regex.search('ip address 10.0.1.2/32')
>>> match.group('address')
'10.0.1.2'
>>> match.group('cidr')
'32'
>>> "".join((match.group('address'), match.group('slash'), match.group('cidr')))
'10.0.1.2/32'

There's ways of not using just regex, of course. Here's some conditions that you could check (this one doesn't find inline, just validates the passed address is valid).

First check is that each char in the address is a digit or a '.'

Next checking that there are exactly 3 '.'

The next two checks check that each octet is between 0 and 255.

And the last check is that no octets are prepended with a '0'

def validate_ipv4_address(address):
    return all(re.match('\.|\d', c) for c in address) \
        and address.count('.') == 3 \
        and all(0 <= int(octet) <= 255 for octet in address.split('.')) \
        and all((len(bin(int(octet))) <= 10 for octet in address.split('.'))) \
        and all(len(octet) == 1 or d[0] != '0' for octet in address.split('.'))


>>> validate_ipv4_address('255.255.255.255')
True
>>> validate_ipv4_address('10.0.0.1')
True
>>> validate_ipv4_address('01.01.01.01')
False
>>> validate_ipv4_address('123.456.789.0')
False
>>> validate_ipv4_address('0.0.0.0')
True
>>> validate_ipv4_address('-1.0.0.0')
False
>>> validate_ipv4_address('1.1.1.')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''
>>> validate_ipv4_address('.1.1.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''
>>> validate_ipv4_address('1..1.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in validate_ipv4_address
  File "<stdin>", line 4, in <genexpr>
ValueError: invalid literal for int() with base 10: ''

(bitwise, each octet should be 8 bits or less, but each is prepended with '0b')

>>> bin(0)
'0b0'
>>> len(bin(0))
3
>>> bin(255)
'0b11111111'
>>> len(bin(256))
11
Bedraggled answered 23/5, 2019 at 19:42 Comment(0)
F
0

I saw very bad regexes in this page.. so i came with my own:

\b((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b

Explanation:

num-group = (0-9|10-99|100-199|200-249|250-255)
<border> + { <num-group> + <dot-cahracter> }x3 + <num-group> + <border>

Here you can verify how it works here

Ferrel answered 8/8, 2019 at 23:46 Comment(0)
T
0

My [extended] approach → regexp for space-separated IP addresses:

((((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])(\\.(?=\\d)|(?!\\d))){4})( (?!$)|$))+

Uses PCRE look-ahead.

Temperamental answered 19/10, 2020 at 13:27 Comment(0)
S
0

Try this

^(127|10).[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"

Seriate answered 30/5, 2021 at 6:56 Comment(0)
Q
0

This pattern unclude 52 symbols and accept cuncks started with zero.

/^(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])(?:\.|$)){4}\b$/
Quillan answered 9/6, 2021 at 22:0 Comment(0)
W
0

My solution here:

^([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])){3}$

This regex will match:

0.0.0.0
255.255.255.255
123.123.123.123
127.0.0.1
192.168.0.1

But it will NOT match:

192.168.1.01
256.256.256.256
01.01.01.01
Wafd answered 8/10, 2021 at 19:38 Comment(0)
K
0

Just try using URL constructor

const validateIPAddress = (ipAddress) => {
  try {
    new URL(`http://${ipAddress}`);
    return true;
  } catch (error) {
    alert("Wrong IP Address");
    return false;
  }
}
Karolyn answered 17/5, 2023 at 11:18 Comment(0)
H
-2

This is regex works for me:
"\<((([1-9]|1[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([1-9]|1[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))\>"

Hance answered 16/10, 2016 at 18:17 Comment(0)
E
-3

^\\s*[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]\\s*

Ecklund answered 23/1, 2012 at 18:15 Comment(1)
This would match 0987654.3.2.1 too.Monotheism
S
-3
String zeroTo255 = "([0-9]|[0-9][0-9]|(0|1)[0-9][0-9]|2[0-4][0-9]|25[0-5])";

it can contain single digit i.e ([0-9]);  
It can contain two digits i.e ([0-9][0-9]); 
range is (099 to 199)i.e((0|1)[0-9][0-9]); 
range is (200 - 249) i.e (2[0-9][0-9]) ; 
range is (250-255) i.e(25[0-5]);
Southwestwardly answered 3/1, 2017 at 2:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.