I'm wondering if this is the best way to match a string that starts with a private IP address (Perl-style Regex):
(^127\.0\.0\.1)|(^192\.168)|(^10\.)|(^172\.1[6-9])|(^172\.2[0-9])|(^172\.3[0-1])
Thanks much!
Windows. Search for cmd in the Windows search bar, then in the command line prompt, type ipconfig to view the private IP address. Mac. Select system preferences, then click on network to view the private IP address.
\d{1,3}\b will match any IP address just fine. But will also match 999.999. 999.999 as if it were a valid IP address. If your regex flavor supports Unicode, it may even match ١٢٣.
Private addresses include IP addresses from the following subnets: Range from 10.0. 0.0 to 10.255. 255.255 — a 10.0.
Approach: Regex (Regular Expression) In C++ will be used to check the IP address. Specifying a range of characters or literals is one of the simplest criteria used in a regex.
I'm assuming you want to match these ranges:
127. 0.0.0 – 127.255.255.255 127.0.0.0 /8 10. 0.0.0 – 10.255.255.255 10.0.0.0 /8 172. 16.0.0 – 172. 31.255.255 172.16.0.0 /12 192.168.0.0 – 192.168.255.255 192.168.0.0 /16
You are missing some dots that would cause it to accept for example 172.169.0.0
even though this should not be accepted. I've fixed it below. Remove the new lines, it's just for readability.
(^127\.)| (^10\.)| (^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)| (^192\.168\.)
Also note that this assumes that the IP addresses have already been validated - it accepts things like 10.foobar
.
This is the same as the correct answer by Mark, but now including IPv6 private addresses.
/(^127\.)|(^192\.168\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^::1$)|(^[fF][cCdD])/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With