Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Validate IPv4 Address ด้วย Regex ใน C++

โจทย์

ตรวจสอบว่า String เป็น IPv4 Address ที่ถูกต้องหรือไม่ ใช้ Regular Expression

กฎ IPv4

  • 4 กลุ่ม (Octets) คั่นด้วย Dot (.)
  • แต่ละกลุ่ม: 0-255
  • ห้าม Leading Zeros (ยกเว้น "0" ตัวเดียว)
  • ตัวอย่างถูกต้อง: 192.168.1.1, 10.0.0.1, 255.255.255.255
  • ตัวอย่างผิด: 256.1.1.1, 192.168.01.1, 1.2.3

Regex Pattern


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

อธิบาย Pattern

PartMatchRange
25[0-5]250-255250,251,252,253,254,255
2[0-4][0-9]200-249200-249
1[0-9]{2}100-199100-199
[1-9][0-9]10-9910-99 (No leading zero)
[0-9]0-90-9 (Single digit)

โค้ด C++


#include <bits/stdc++.h>
using namespace std;

string validateIPv4(string IP) {
    regex ipv4(R"(^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$)");
    
    if (regex_match(IP, ipv4)) {
        return "IPv4";
    }
    return "Not";
}

int main() {
    vector<string> tests = {
        "172.16.254.1",       // Valid
        "172.15.254.2",       // Valid
        "192.168.1.1",        // Valid
        "10.0.0.1",           // Valid
        "255.255.255.255",    // Valid
        "0.0.0.0",            // Valid
        "312.25.12.1",        // Invalid (>255)
        "192.168.01.1",       // Invalid (Leading zero)
        "192.168.1.00",       // Invalid (Leading zero)
        "192.168@1.1",        // Invalid (Wrong separator)
        "1.2.3",              // Invalid (Only 3 octets)
        "1.2.3.4.5",          // Invalid (5 octets)
        "256.1.1.1",          // Invalid (>255)
        "-1.2.3.4",           // Invalid (Negative)
        "192.168.1.",         // Invalid (Trailing dot)
        ".192.168.1.1",       // Invalid (Leading dot)
    };
    
    for (auto& ip : tests) {
        cout << ip << " → " << validateIPv4(ip) << endl;
    }
    
    return 0;
}

วิธีอื่น: Parsing แบบ Manual (ไม่ใช้ Regex)


bool isValidIPv4Manual(string IP) {
    int count = 0, num = 0, len = IP.length();
    bool hasDigit = false;
    
    for (int i = 0; i <= len; i++) {
        char c = (i < len) ? IP[i] : '.';
        
        if (c == '.') {
            if (!hasDigit) return false; // Empty octet
            if (num > 255) return false;
            if (IP[i - 1] == '0' && hasDigit && (i - 1 > 0 && IP[i-2] != '.')) {
                // Check leading zero: "01", "00" invalid but "0" ok
                // Simpler: track original string length of octet
            }
            count++;
            num = 0;
            hasDigit = false;
        } else if (isdigit(c)) {
            if (!hasDigit && c == '0' && i+1 < len && isdigit(IP[i+1])) {
                return false; // Leading zero
            }
            num = num * 10 + (c - '0');
            hasDigit = true;
        } else {
            return false; // Invalid character
        }
    }
    return count == 4;
}

ผลลัพธ์

172.16.254.1 → IPv4
172.15.254.2 → IPv4
192.168.1.1 → IPv4
10.0.0.1 → IPv4
255.255.255.255 → IPv4
0.0.0.0 → IPv4
312.25.12.1 → Not
192.168.01.1 → Not
192.168.1.00 → Not
192.168@1.1 → Not
1.2.3 → Not
1.2.3.4.5 → Not
256.1.1.1 → Not
-1.2.3.4 → Not
192.168.1. → Not
.192.168.1.1 → Not

สรุป

IPv4 Regex ต้องจัดการ Range 0-255 และ No Leading Zeros อย่างถูกต้อง Pattern แบบ Manual Parsing เร็วกว่าและควบคุมได้ละเอียดกว่า - LeetCode 468 (Validate IP Address)