2013-02-01 88 views
3

我有IPv6地址的正則表達式下面正則表達式地址

IPV4ADDRESS  [ \t]*(([[:digit:]]{1,3}"."){3}([[:digit:]]{1,3}))[ \t]* 
x4    ([[:xdigit:]]{1,4}) 
xseq    ({x4}(:{x4}){0,7}) 
xpart   ({xseq}|({xseq}::({xseq}?))|::{xseq}) 
IPV6ADDRESS  [ \t]*({xpart}(":"{IPV4ADDRESS})?)[ \t]* 

給出它是正確的IPv6的所有格式地址,包括

的IPv6
1) non-compressed IPv6 addresses 
2) compressed IPv6 addresses 
3) IPv6 addresses in legacy formats.(supporting IPv4) 

理想的例子中遺留格式地址將是

2001:1234::3210:5.6.7.8 

    OR 
2001:1234:1234:5432:4578:5678:5.6.7.8 

As you can see above there are 10 groups separated by either `":" or ".".` 

而不是正常的IPv6地址中的8組。這是因爲最後4個由「」隔開的組。應該被壓縮成最低有效的32位IPv6地址。因此我們需要10個組來滿足128位。

然而如果我使用下面的地址格式

2001:1234:4563:3210:5.6.7.8 

這裏,每個組由「:」分隔表示由separted 16 bits.the最後四個基團「」代表8比特。總比特數是64 + 32 = 96比特.32比特丟失

正則表達式接受它作爲有效的IPv6地址格式。我無法弄清楚如何修正正則表達式丟棄這樣的價值。任何幫助都非常感謝。

+1

你能否解釋提供的否定例子有什麼問題? –

+0

上面解釋了這個例子。由「:」分隔的每個組代表16位。最後的四個組由「。」分隔。代表8比特。總比特數是64 + 32 = 96比特。丟失32比特。 – liv2hak

+1

那麼,它也接受:: 0:999.999.999.999這樣的廢話。 – nneonneo

回答

5

這裏是爲RFC 3986給出,隨後在RFC 5954肯定了IPv6地址的語法:

IPv6address =        6(h16 ":") ls32 
       /      "::" 5(h16 ":") ls32 
       /[    h16 ] "::" 4(h16 ":") ls32 
       /[ *1(h16 ":") h16 ] "::" 3(h16 ":") ls32 
       /[ *2(h16 ":") h16 ] "::" 2(h16 ":") ls32 
       /[ *3(h16 ":") h16 ] "::" h16 ":" ls32 
       /[ *4(h16 ":") h16 ] "::"    ls32 
       /[ *5(h16 ":") h16 ] "::"    h16 
       /[ *6(h16 ":") h16 ] "::" 

h16   = 1*4HEXDIG 
ls32   = (h16 ":" h16)/IPv4address 
IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet 
dec-octet  = DIGIT     ; 0-9 
       /%x31-39 DIGIT   ; 10-99 
       /"1" 2DIGIT   ; 100-199 
       /"2" %x30-34 DIGIT  ; 200-249 
       /"25" %x30-35   ; 250-255 

利用這一點,我們可以建立IPv6地址符合標準的正則表達式。

dec_octet  ([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]) 
ipv4address ({dec_octet}"."){3}{dec_octet} 
h16   ([[:xdigit:]]{1,4}) 
ls32   ({h16}:{h16}|{ipv4address}) 
ipv6address (({h16}:){6}{ls32}|::({h16}:){5}{ls32}|({h16})?::({h16}:){4}{ls32}|(({h16}:){0,1}{h16})?::({h16}:){3}{ls32}|(({h16}:){0,2}{h16})?::({h16}:){2}{ls32}|(({h16}:){0,3}{h16})?::{h16}:{ls32}|(({h16}:){0,4}{h16})?::{ls32}|(({h16}:){0,5}{h16})?::{h16}|(({h16}:){0,6}{h16})?::) 

聲明:未經測試。

+0

+1另請參閱我的文章:[正則表達式URI驗證](http://www.jmrware.com/articles/2009/uri_regexp/URI_regex.html)其中包括IPv6的正則表達式以及[RFC-3986](http://tools.ietf.org/html/rfc3986)中指定的所有其他URI組件。 – ridgerunner